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

后端 未结 7 1231
轻奢々
轻奢々 2021-01-20 23:44

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

相关标签:
7条回答
  • 2021-01-21 00:18

    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

    0 讨论(0)
  • 2021-01-21 00:18
    $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
    }
    
    0 讨论(0)
  • 2021-01-21 00:23

    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.

    0 讨论(0)
  • 2021-01-21 00:27

    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.

    0 讨论(0)
  • 2021-01-21 00:35

    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.

    0 讨论(0)
  • 2021-01-21 00:35

    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');
    
    0 讨论(0)
提交回复
热议问题