Tutorial :Shortest way to compare 2 dates in dd/mm/yyyy format



Question:

can anyone suggest the neatest way to do this comparison? I need to test if a date provided in dd/mm/yyyy format is less than a fixed date, e.g 01/05/2009 - I know I can convert these to unix time format using strtotime, then make the comparison, but I'm curious if there is a quicker way to do it - many thanks, just looking for a hint to improve my code!


Solution:1

There's probably not a shorter way code wise, and I wouldn't bother optimizing this unless you're sure it's a bottleneck.

However, as long as you're sure it will always be the exact same format (including 2 digits for month and day and with 0s) you should be able to reorder the string to put the year first, then the month, and then the day, and then just compare the strings.

However, I'm not sure this would be faster than just letting the libraries convert to unix time and then comparing those.

If you can change the format that the dates are stored in, you could define them as yyyy/mm/dd and then just compare the strings.


Solution:2

One option is just to reverse the format - create a string of the form

yyyy/mm/dd  

That's a sortable format, so you can just do an ordinal string comparison. Of course, this means you won't detect invalid data etc.


Solution:3

I think that your solution of converting it to Epoch then doing a comparison is as fast and as clean as your going to get.


Solution:4

if you want to improve your code, I would suggest you to use DateTime class. It's been introduced in php 5.2.0 (so, it still might not be supported on all servers)

in php 5.3.0 you can write something like this:

$d1 = DateTime::createFromFormat('d/m/Y', '02/03/2009');  $d2 = DateTime::createFromFormat('d/m/Y', '02/05/2009');  $interval = $d1->diff($d2);  echo $interval->format('%R%d days');  


Solution:5

Well, you could use the PHP date class, but I am not sure it would be any better than you current solution...

http://php.net/manual/en/book.datetime.php


Solution:6

use this method

yearmonthday

you have 01.05.2010 and 03.07.2010

and to compare : 20100501 <= or => 20100703


Solution:7

$fixedDate = '01/05/2009';  $variableDate = '28/04/2010';    // Now we do our timestamping magic!  $fixedDate = implode('', array_reverse(explode('/', $fixedDate)));  $variableDate = implode('', array_reverse(explode('/', $variableDate)));    if ($variableDate < $fixedDate) // 20100428 < 20090501  {    // there you go  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »