Skip to content Skip to sidebar Skip to footer

How To Get Current Date Time Of Other Country In Client Side Code In Javascript?

I want to get Dubai's Current date time In India, Lets Look bellow code you can get better Idea, var compareDate = r.get('updatedate'); var diff = new Date() - new Date(compareDate

Solution 1:

Javascript has no access to time zones except local and UTC. There are a multitude of workarounds.

  1. You could check whether you can convert every date into UTC on the server, send it to the client in UTC and convert it from UTC to local there. But if the dates should be displayed in Dubai time zone, this is not feasible.

  2. The easiest way to get current server time to the client is to transmit it from the server to the client; or calculate the difference server-side and send it to the client.

  3. If you need just-in-time updates, which means transmission of time is not feasible, the next-best way is to know the current difference between the two time zones.

    This requires the following:

    • You have to send to the client once the difference between the server time zone and UTC, e.g. 180 minutes.
    • You can calculate on the client the difference between client time zone and UTC using new Date().getTimezoneOffset(), e.g. 270.
    • Then you can subtract the two to get the difference between client and server.
    • And now you can calculate on the client side.

    Please note that this breaks when the server switches time zone offset during daylight saving change. Should not be an issue in your case, since Dubai does not have DST, but in the general case.

  4. If you really need full timezone availability on the client, check out moment.tz. You will have to see how you can get the server to understand moment.tz time zones and vice versa. In my case, I completely dropped the builtin time zones of moment.tz, converted all server time zones into the moment.tz format on the server side and transmitted them as JSON to the client.

Solution 2:

Dubai's timezone is UTC+4

Javascript Date objects all have the function getTimezoneOffset() (MDN), which gives you the offset of the client's time against UTC, in minutes.

Knowing the real offset, we can adjust client's time to whichever timezone we want.

Example:

var compareDate = r.get('updatedate'); //Dubai's date.var localTime = newDate();
var offset = localTime.getTimezoneOffset();

var dubaiOffset = compareDate.getTimezoneOffset() - offset; //calculate local time's offset against Dubai.var diff += (newDate() + dubaiOffset*60000) - newDate(compareDate);
diff /= 60000; 
// The rest of your code goes here.

Post a Comment for "How To Get Current Date Time Of Other Country In Client Side Code In Javascript?"