日期和时间的问题是对话取决于当地时区

Issue with date and time is conversation depending on local timezone

你好,今天我遇到了时间戳转换问题。在我的网络表单中,我使用了 bootstrap-datepicker,用户可以在其中选择日期和时间.之后,我将这些值 moment.js 转换为 unix timestamp 并将其传递给 PHP 页面。在 PHP 页面中,如果用户在不同的国家/地区,则值不同,最后在数据库中插入错误的值。 所以这就像服务器时区是 Latvia/Riga GMT+2 而来自 Georgia/Tbilisi 的用户有 GTM+4。他正在选择开始日期 12.01.2017 15:00,Moment.js 将其传递到 PHP 页面中插入开始日期的 DB 值 12.01.2017 13:00.

这是来自 js 的代码

var start_date = $("#start_date").val();
var start_time = $("#start_time").val();
var start = moment.utc(start_date + ' ' + start_time, "DD.MM.YYYY HH:mm").tz("Europe/Riga");

之后 var 通过 ajax 传递给 PHP 脚本,例如 start.unix()

在PHP中接收

$startDate      = date('Y-m-d H:i:s', $_GET['start']);

时间提前2小时收到.. 我该怎么做才能让用户选择世界上任何地方的时间 PHP 插入数据库,因为它选择正确而无需时区转换。

永远不要传递带有 client-to-server 时区的日期,在这种情况下始终让服务器做主,否则数据库中将不可避免地出现不一致问题。

你要么:

  • 始终使用 UTC+0 日期。
  • 使用代表日期的关键字(即昨天、现在、两天前)。

使用关键字可以让服务器根据 UTC+0 时区决定您想要的日期。

TL;DR;

始终使用 UTC+0 日期时间并根据用户所在的时区进行转换 server/client-side(这是您的偏好)。

您可以使用以下 JS 在 JS 中获取客户端时区:

var time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var start_date = $("#start_date").val();
var start_time = $("#start_time").val();

在PHP中:

function getDateTime($start_date, $start_time, $time_zone) {
    $dateTime = $start_date . ' ' . $start_time;
    $date = new DateTime($dateTime, new DateTimeZone($time_zone));

    $serverTimeZone = date_default_timezone_get();
    $date->setTimezone(new DateTimeZone($serverTimeZone));
    return $date->format('Y-m-d H:i:sP');
}

这可能有助于您同步时区