简体   繁体   中英

PHP - Comparing Dates

In my PHP script I get a date string from my iOS app, as such:

$myTime     = $app->request()->post('myTime'); // 2016-08-15 20-02
$date = date('Y-m-d H-i', strtotime($myTime));

Now that I have the date from my iOS app, I want to do a check on my database for a booking/reservation, and check if the date from my iOS app falls between a period +/- 10 hours of the date from database:

// $book['book_datetime'] is confirmed 2016-08-15 20:38:00

$plusTen = date('Y-m-d H:i:s', strtotime($book['book_datetime'])+36000);
$minusTen = date('Y-m-d H:i:s', strtotime($book['book_datetime'])-36000);

if((strtotime($date) > strtotime($minusTen)) && (strtotime($date) < strtotime($plusTen))) {

     //should be true

} else {

}

The if statement should be true, however it's not working. Can anyone tell me why?

Your

$date = date('Y-m-d H-i', strtotime($myTime));

wont work as you have a non standard time format.

Instead use the DateTime class like this to get a timestamp from your odd date time format.

$myTime = $app->request()->post('myTime'); // 2016-08-15 20-02
$mydt   = DateTime::createFromFormat('Y-m-d H-i', $myTime);

$date = $mydt->getTimestamp();

Re you comment:

I ran this code from the CLI and it works

<?php
$myTime = '2016-08-15 20-02';
$mydt   = DateTime::createFromFormat('Y-m-d H-i', $myTime);

echo $mydt->getTimestamp() . PHP_EOL;
echo $mydt->format('Y-m-d H:i:s') . PHP_EOL;

If you get an error then maybe you datetime value from $app->request()->post('myTime'); is not in the format you think

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM