简体   繁体   中英

Issue with date and time is conversation depending on local timezone

Hello today I encountered an issue with time stamp conversions.. In my web form I'm using an bootstrap-datepicker where users can pick date and time. Afterwards I convert those values with moment.js to unix timestamp and pass it to PHP page. In the PHP page if the user is in different country the value is different and in the end in database is inserted wrong value. So it's like the server timezone is Latvia/Riga GMT+2 and user from Georgia/Tbilisi has GTM+4 . He's selecting start date 12.01.2017 15:00 , Moment.js passes it to PHP page in the DB value of start date is inserted 12.01.2017 13:00 .

Here is code from 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");

afterwards var is passed via ajax to PHP script like start.unix()

In PHP it receives

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

And time is received by 2 hours earlier.. What can I do so the user selects time from anywhere on the world PHP inserts in DB as it selected correctly without timezone conversion.

You should never pass dates with timezones from client-to-server, always have the server be the boss in this case, otherwise you're inevitably going to have inconsistency issues in your database.

You either:

  • Always use UTC+0 dates.
  • Use keywords that represent a date (ie. yesterday, now, two days ago).

Using a keyword allows you to make the server decide which date do you want based on UTC+0 timezone.

TL;DR;

Always use UTC+0 datetimes and convert them server/client-side (it's your preference) depending on which timezone a user is on.

You can use following JS to get Client Timezone in JS:

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

In 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');
}

This might help you to sync timezone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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