JSFiddle - React, Tailwind, and code Playground

by mark_brightsoft

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data-1970-2030.js"></script>
<div id="localTime">

</div>
<div id="utcTime">

</div>
<div id="momentTzTime1">

</div>

<div id="momentTzTime2">

</div>

JavaScript

$(function(){

//local time zone is Asia/Ho_Chi_Minh

//today is Oct 20th, and user A create a booking starting at 10 AM Nov 4th
//we just use local date toString method and send this string to server
let localTimeStringSentToServer = new Date('2021-11-04 10:00:00').toString();

//we can see that localTimeStringSentToServer has the local time part, and a time zone offset part
$("#localTime").text("Local time converted to string: " +localTimeStringSentToServer);

//today is Oct 20th, and user A create a booking starting at 10 AM Nov 4th
//we convert this local time to a UTC string (RFC 1123) and send this string to server
let utcTimeStringSentToServer = new Date('2021-11-04 10:00:00').toUTCString();
$("#utcTime").text("Local time converted to UTC string: " + utcTimeStringSentToServer);


//assume server send back the localTimeStringSentToServer and we translate to Stockholm timezone
//this result is WRONG
$("#momentTzTime1").text("Translated to Stockholm time from saved localTimeString: " + moment.tz(localTimeStringSentToServer, 'Europe/Stockholm').format('LLL'));

//assume server send back the utcTimeStringSentToServer and we translate to Stockholm timezone
//this result is CORRECT
$("#momentTzTime2").text("Translated to Stockholm time from saved utcTimeString: " + moment.tz(utcTimeStringSentToServer, 'Europe/Stockholm').format('LLL'));

//As you can see UTC time string is a better option to use.
});