doushouhe7072 2015-11-06 19:47
浏览 14
已采纳

php - 将输入的日期与当前日期进行比较并得出错误的结果,因为服务器时区与输入的时区不同

I have a form where the user will enter a date and time for an email campaign. As part of the form validation, I am confirming that the user enters a future date.

The current servers default time zone is UTC.

The user will enter the scheduled date and time as a string (generated by a JQuery date and time picker).

The entered string is converted to a timestamp, and then compared with the current date and time.

If the entered date & time is before the current date & time, the form is not submitted and the user is notified to re-enter a future date.

The problem is, if the user enters a future time & date and time within the next 8 hours of the current time (which is pacific time zone), the system will think it's in the past because the server time zone is UTC (which is 8 hours ahead of PST).

I tried to convert the user input to UTC using gmdate like below:

//$timeEntered is a string, like 2015/11/06 19:27:21:
$timeEntered = $_POST['date_and_time'] 
$theEnteredTimeInUnixTimestamp = strtotime ( $timeEntered );
$enteredTimeInGMT =  gmdate('Y-m-d H:i:s', $theEnteredTimeInUnixTimestamp );

but it won't convert it. Should I just add 8 hours to the entered date and time so it matches the current server time (UTC)? That would be stupid because this will change during daylight savings time.

Should I change the current server time zone to Pacific time while doing the comparison, so the time zones match? That will give unexpected results if the users are in different time zones. I'm not sure how to handle this to make it reliably compare the entered time with the current time and give a correct result.

  • 写回答

2条回答 默认 最新

  • dsgd5756 2015-11-06 20:13
    关注
    $user_date_str = '2015/11/06 19:27:21';
    $user_tz = 'America/Los_Angeles';
    $server_tz = 'UTC';
    
    // Get a DateTime object for the user entered time
    $user_datetime = new DateTime($user_date_str, new DateTimeZone($user_tz) );
    // Change time zone to the same as the server
    $user_datetime->setTimeZone(new DateTimeZone($server_tz));
    
    // Get a DateTime object for the current server time
    $server_datetime = new DateTime();
    // If the PHP timezone isn't set correctly, you can also do:
    //$server_datetime = new DateTime(null, new DateTimeZone($server_tz) );
    
    // Now compare
    if ($user_datetime < $server_datetime) {
        // handle the error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题