John Davidson

php - Check if date has past other date don't work in certain situations

0 comments
Message:


I have done research on how to figure out how I can use a if else statement to determine if a certain date has past another date or not but I notice this script works how it should work but if the day is a certain number for example 2 in the $present_time variable then it gives out the right output which is the else statement


This works


INPUT


<?php

$time_format = 'n-j-Y g:i A';
$time_zone = 'America/phoenix';

$date = DateTime::createFromFormat($time_format, '9-2-2021 11:28 AM', new DateTimeZone($time_zone));
$present_time = $date->format($time_format);

$date = DateTime::createFromFormat($time_format, '9-21-2021 9:57 PM', new DateTimeZone($time_zone));
$end_time = $date->format($time_format);

if($present_time > $end_time) {

echo 'Present time has pass the end time.';

}

else{

echo 'Present time has not pass the end time.';

}

?>

OUTPUT


Present time has not pass the end time.


but if I change the $present_time variables day to a 3 then I get an unexpected output which is the if statement and I should not get the else statement to show because the $end_time obviously has a later date.


INPUT


<?php

$time_format = 'n-j-Y g:i A';
$time_zone = 'America/phoenix';

$date = DateTime::createFromFormat($time_format, '9-3-2021 11:28 AM', new DateTimeZone($time_zone));
$present_time = $date->format($time_format);

$date = DateTime::createFromFormat($time_format, '9-21-2021 9:57 PM', new DateTimeZone($time_zone));
$end_time = $date->format($time_format);

if($present_time > $end_time) {

echo 'Present time has pass the end time.';

}

else{

echo 'Present time has not pass the end time.';

}

?>

OUTPUT


Present time has pass the end time.


So how can I get this to work properly to show the correct condition properly in these situations.


I got this method based on this tutorial


https://write.corbpie.com/php-check-if-current-date-time-has-passed-a-set-date-time/


but I need to use the hyphen character so that is why it looks a little different from that tutorial.



My Answer:
You can use the `strtotime()` function in PHP to convert the dates to Unix timestamps and then compare them to check if one date has passed another date. Here's an example code snippet to demonstrate this:

php
$date1 = '2022-01-01';
$date2 = '2022-02-01';

if (strtotime($date1) < strtotime($date2)) {
echo "Date 1 has passed Date 2";
} else {
echo "Date 1 has not passed Date 2";
}


In this example, if Date 1 is before Date 2, it will output "Date 1 has passed Date 2". Otherwise, it will output "Date 1 has not passed Date 2". You can modify the dates in the code snippet to test different scenarios.

Rate this post

4 of 5 based on 8481 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us