简体   繁体   中英

Comparing Two Dates in PHP

I have problem in comparing two dates. User will choose date from Datepicker with format ('Ym-d'). If input is not equal to the current date then error message will showed up else output will be displayed.

I have this code:

$today = date("Y-m-d");
$date = $_REQUEST['selected_date']; // date selected
$first = strtotime($today);             
$second = strtotime($date);

if ($first != $second){
    //error message 
}else{
    //some code
}       

This works fine in local but when i try to upload it, its not working anymore. Instead, the previous date can be accepted not the current date.

Probably the timezone is set differently on the server than from your local machine.

Try printing out the values of $first and $second .

You can (and should) set the timezone used by PHP with date_default_timezone_set() if you're using any of the old-style PHP date functions ( date , strtotime etc).

Though I recommend using the DateTime & DateTimeZone classes with new code, they're nicer to work with, especially if you're doing anything involving multiple timezones.

Is there any possibility that the server is in a different time zone than where the request is coming from? I'd think this could lead to a mismatch.

Hopefully I understand your situation correctly. Attacking this directly will fail a lot of times because the server time zone (which you get through date() ) will be different from the client time zone. To avoid this problem you need to send the client time to your server via javascript. jQuery example may look like this:

var date = new Date();

$.post("index.php", { today: (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear()}, function(data) {

alert(data); //server response here

});

on the server you get your client's today date as a string via $_POST['today'] . Then you can decide what to do with it and output it to your client.

Alternatively, the problem you are describing can be solved just by JavaScript without sending it to your server unless you want to do something with it on your server

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