简体   繁体   English

在PHP中比较两个日期

[英]Comparing Two Dates in PHP

I have problem in comparing two dates. 比较两个日期时出现问题。 User will choose date from Datepicker with format ('Ym-d'). 用户将从Datepicker中选择格式('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 . 尝试打印$first$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). 如果您使用的是任何老式的PHP日期函数( datestrtotime等),则可以(并且应该)使用date_default_timezone_set() )设置PHP使用的时区。

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. 尽管我建议将DateTimeDateTimeZone类与新代码一起使用,但它们更适合使用,尤其是当您执行涉及多个时区的任何事情时。

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. 直接进行攻击将失败很多次,因为服务器时区(通过date()获得)与客户端时区不同。 To avoid this problem you need to send the client time to your server via javascript. 为避免此问题,您需要通过javascript将客户端时间发送到您的服务器。 jQuery example may look like this: jQuery示例可能如下所示:

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'] . 在服务器上,您可以通过$_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 另外,除非您要在服务器上进行处理,否则只需使用JavaScript即可解决您所描述的问题,而无需将其发送到服务器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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