satya
satya

Reputation: 1959

compare dates not working

Hallo,

I am comparing 2 dates. It is clear that $db_minus7 is greater so the value of $can_invoiced should be 'maybe' but it is 'Yes'. When i execute.

<?php

$db_minus7 = '2010-07-05 09:45:29.420';
$completion_date = '30.07.2009';
if(date("m-d-Y",strtotime($db_minus7)) > date("m-d-Y",strtotime($completion_date))) {
    $can_invoiced = 'maybe';
} else {
    $can_invoiced = 'Yes';
}

echo $can_invoiced;

?>

please help

Upvotes: 4

Views: 4443

Answers (4)

Lo&#239;c F&#233;vrier
Lo&#239;c F&#233;vrier

Reputation: 7750

Dont' use "m-d-Y" but "Y-m-d".

01-01-2010 is lower than 02-01-2009 (bad !) but 2010-01-01 is not lower than 2009-01-02 (good !).

Upvotes: 3

Hannes
Hannes

Reputation: 8237

Never Compare Dates as strings, even if it works for your Testcases it will fall on your feets sooner or later ... or maybe... richard stallman will hunt you down, i don't know ...

if(strtotime($db_minus7) > strtotime($completion_date)) {
    $can_invoiced = 'maybe';
} else {
    $can_invoiced = 'Yes';
}

Upvotes: 0

oezi
oezi

Reputation: 51797

why don't you just compare the times instad of formating them again like this:

if(strtotime($db_minus7) > strtotime($completion_date)) {
    $can_invoiced = 'maybe';
} else {
    $can_invoiced = 'Yes';
}

EDIT:

if you want to use date(), use "Ymd" or "Y-m-d" as pattern because it's string-comparision, and this is the logical order to work with (arrange the patterns from "big"(years) to small (days... or maybe seconds, if you need));

Upvotes: 7

Mark Baker
Mark Baker

Reputation: 212412

Compare the dates as datestamps, not as strings:

if(strtotime($db_minus7) > strtotime($completion_date)) { 

If you have to compare the dates as strings, then use Y-m-d rather than m-d-y

Upvotes: 1

Related Questions