Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtotime: Check for time

I have a voucher system, where I can enter a date or a date with a time. There should be all valid formats allowed, for example this ones:

  • 01.01.2016
  • 01.01.2016 00:00:00

This I no problem, if I have the start date for a voucher, but it is a problem if I had the end date. I use strtotime to convert the user input to a UNIX timestamp.

If you just enter the date as end date, it should be the end of the day used. Like this:

01.01.2016 -> 01.01.2016 23:59:59 -> 1451689199

But - and this is my problem - strtotime returns the same timestamp of course for 01.01.2016 and 01.01.2016 00:00:00. And when the user enters a time, this time should be used of course.

01.01.2016
1451602800
-> should go to 1451689199

01.01.2016 00:00:00
1451602800
-> is correct

01.01.2016 23:59:59
1451689199
-> is correct

I need a possibility to check if the string - that is converted by strtotime - has a time explicit in it. I searched for a function for this without success, even the DateTime class has no method for this (hasTime() or something like this).

As I said before, all date/time formats strtotime supports should be supported by this function also.

This question is NOT a duplicate! I want to check if there is any time specified explicit. The question which should be the duplicate is a basic question for PHP beginners and has exactly nothing to do with this problem!

like image 897
Richard Avatar asked Nov 09 '22 09:11

Richard


1 Answers

I'd test the length of the string before calling strtotime and add 23:59:59:

$dates = array('01.01.2016','01.01.2016 23:59:59','01.01.2016 10:25:30');
foreach($dates as $date) {
    echo "date=$date\n";
    if (strlen($date) > 10) {
        echo strtotime($date),"\n";
    } else {
        echo strtotime($date . ' 23:59:59'),"\n";
    }
}

Output:

date=01.01.2016
1451689199
date=01.01.2016 23:59:59
1451689199
date=01.01.2016 10:25:30
1451640330
like image 197
Toto Avatar answered Nov 14 '22 23:11

Toto