Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Date comparison

Status
Not open for further replies.

scousethemoose

Programmer
Jul 14, 2002
69
AU
Hi heres my problem hopefully someone can point me in the right direction.

I get the current date and time using date("H:i m/d/Y"). I then try to compare it to another date and time I create myself.

eg date("H:i m/d/Y", mktime(21,00,00,11,28,2004))

Heres a scaled down version of my code

Code:
<?php

$local = date("H:i m/d/Y");
$depart = date("H:i m/d/Y", mktime(21,0,0,11,28,2004));

//compare dates

if($local >= $depart)
{
   print 'You have left the country';
}

?>

For some reason nomatter what I do it evaluates the if as if it were true. Any ideas? Maybe a better alternative I havent considered.
 
The type of comparison you are doing is a string comparison of two date strings. But the date strings you are generating are useless for the purposes of the comparison.

"21:00 11/28/2004", for example, will always be evaluated as coming before "22:00 10/17/2003" because the string comparison operator starts at the first character, alphabetically comparing the strings, and "21" thus comes before "22", regardless of what follows in the strings.

Try something like:
Code:
<?php
$local = date("[COLOR=red]YmdHis[/color]");
$depart = date("[COLOR=red]YmdHis[/color]", mktime(21,0,0,11,28,2004));

//compare dates

if($local >= $depart)
{
   print 'You have left the country';
}

?>

The date format string "YmdHis" will generate a date string like "20041128210000", which has the nice feature that date order and alphabetical order are one and the same. You can add other characters, so long as the order of date components is largest (year) to smalles (seconds)


Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Please read here:

I know you might find it boring that I simply do not provide you with the sollution, but I think it's important to understand why it works.

For that, you need to read those few lines, included the examples.. Then you will be the master of comparing dates!

Olav Alexander Mjelde
Admin & Webmaster
 
Thank-you both for your suggestions. I'll have a look at both of them.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top