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 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗