如何通过提交表单将用户本地时间从JavaScript有效传递到PHP?
解决用户本地时间传递到PHP并转为DateTime的问题
问题场景
我正在开发一款工具,使用服务器时间会因时区差异让用户产生困惑,因此希望将用户本地系统时间传递到PHP,存入数据库的DATETIME字段时基于该本地时间。
之前尝试过的操作:
- 前端用jQuery在表单提交前存入时间:
$('input[name=now]').val('@' + Math.round(new Date().getTime()/1000));
- PHP端处理代码:
$local_time = (int)$_REQUEST['now']; $today = new DateTime($local_time);
折腾一小时后仍未解决,要么抛出错误要么忽略传入值直接使用服务器时间,当前报错:
Fatal error: Uncaught Exception: Failed to parse time string (0) at position 0 (0): Unexpected character in {pathtofile}.php:1394
也尝试过传递toGMTString、toISOString等格式,均未成功。
问题根源
- 前端给时间值添加了
@前缀,后端转成整数时会忽略非数字字符,导致$local_time变为0,触发DateTime解析失败。 - PHP的
DateTime构造函数直接传入整数时,会被当作普通字符串解析而非Unix时间戳,引发格式错误。
正确解决方案
方案1:传递纯Unix时间戳(推荐)
前端代码
移除@前缀,直接传递秒级Unix时间戳:
$('input[name=now]').val(Math.round(new Date().getTime() / 1000));
PHP代码
两种方式解析时间戳:
// 方式一:用createFromFormat指定Unix时间戳格式 $local_time = (int)$_REQUEST['now']; $today = DateTime::createFromFormat('U', $local_time); // 方式二:给时间戳添加@前缀,让DateTime识别为Unix时间戳 $local_time = (int)$_REQUEST['now']; $today = new DateTime("@$local_time");
方案2:传递ISO 8601格式字符串
前端传递标准ISO格式字符串,PHP可直接解析:
前端代码
$('input[name=now]').val(new Date().toISOString());
PHP代码
$local_time = $_REQUEST['now']; $today = new DateTime($local_time);
数据库存储注意事项
如果存入MySQL的DATETIME类型,需确保时区正确,可手动设置:
// 根据用户本地时区调整,示例为上海时区 $today->setTimezone(new DateTimeZone('Asia/Shanghai')); // 转换为MySQL兼容的DATETIME格式 $db_time = $today->format('Y-m-d H:i:s');
内容的提问来源于stack exchange,提问作者not_a_generic_user
相关产品推荐
相关产品推荐

