Issue with date and time is conversation depending on local timezone

417 views Asked by At

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.

2

There are 2 answers

1
GiamPy On BEST ANSWER

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.

0
Sujit Baniya 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