Почему бы не сделать это проще, используя DateTime
объекты ?
Дополнительно: Относительные условия для strtotime
, DateTime
и date_create
.
Я быстро создал несколько примеров с некоторыми комментариями для вас.
<?php
$today = new DateTime('today'); // comes with today's date and 00:00:00 for time
$now = new DateTime('now'); // comes with today's date and current time
if ($now > $today) {
echo 'Now is later than the day\'s start... <br />';
}
echo '<hr />';
$testDates = [
'2018-08-07',
'2018-08-31',
];
// Compare with "now" -> ignores time
foreach ($testDates as $testDate) {
// Create new DateTime based on given string and sets time to 00:00:00
$testDate = (new DateTime($testDate))->setTime(0, 0, 0);
if ($testDate > $today) {
echo 'Test date "' . $testDate->format('Y-m-d') . '" is greater than today: ' . $today->format('Y-m-d') . '<br />';
}
}
echo '<hr />';
$testDatesWithTime = [
'2018-08-07 12:33:33',
'2018-08-29 08:00:00', // Today - has already been
'2018-08-29 22:00:00', // Today - is yet to come
'2018-08-30 22:00:00',
];
// Compare with "now" -> take time into account
foreach ($testDatesWithTime as $testDate) {
// Create new DateTime based on given string and sets time
$testDate = new DateTime($testDate);
if ($testDate > $now) {
echo 'Test date "' . $testDate->format('Y-m-d H:i:s') . '" is greater than today: ' . $now->format('Y-m-d H:i:s') . '<br />';
}
}
Выход сверху:
Now is later than the day's start...
Test date "2018-08-31" is greater than today: 2018-08-29
Test date "2018-08-29 22:00:00" is greater than today: 2018-08-29 09:55:06
Test date "2018-08-30 22:00:00" is greater than today: 2018-08-29 09:55:06