ChatGPT解决这个技术问题 Extra ChatGPT

Convert date to another timezone in JavaScript

I am looking for a function to convert date in one timezone to another.

It need two parameters,

date (in format "2012/04/10 10:10:30 +0000")

timezone string ("Asia/Jakarta")

The timezone string is described in http://en.wikipedia.org/wiki/Zone.tab

Is there an easy way to do this?

Find the UTC offset of a given city. stackoverflow.com/questions/3002910/…
I want to to calculate not just the UTC offset but also Daylight saving/summer time. So the time will return correctly.
Off set of your time zone using unix date command: date +%s -d '1 Jan 1970'

M
Michael Scheper

Here is the one-liner:

function convertTZ(date, tzString) { return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString})); } // usage: Asia/Jakarta is GMT+7 convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time) // Resulting value is regular Date() object const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") convertedDate.getHours(); // 17 // Bonus: You can also put Date object to first arg const date = new Date() convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.

This is the MDN Reference.

Beware the caveat: function above works by relying on parsing toLocaleString result, which is string of a date formatted in en-US locale , e.g. "4/20/2012, 5:10:30 PM". Each browser may not accept en-US formatted date string to its Date constructor and it may return unexpected result (it may ignore daylight saving).

Currently all modern browser accept this format and calculates daylight saving correctly, it may not work on older browser and/or exotic browser.

side-note: It would be great if modern browser have toLocaleDate function, so we don't have to use this hacky work around.


I changed answer to this, since this is correct and standard method without using any library.
The MDN documentation clearly says that the only timezone that is required to be recognized in all implementations is UTC. (stackoverflow.com/questions/10087819/…) Clicking the [Run code snippet] button in IE11 produces an error.
This answer shows correctly passing a time zone to toLocaleString, but then it very incorrectly shows passing that string back into the Date constructor. That is asking for trouble. The Date string parser is not required to accept locale specific formats, and the input would be treated as if it were in the local time zone. Don't do that. Just use the string output from the first toLocalString call.
@MattJohnson then you can't use getHour() or such methods
This is a flawed approach. It doesn't parse the OP format, it relies on browsers parsing a format that they aren't required to parse, it may incorrectly apply a daylight saving offset and it presents a timestamp as UTC that isn't. The .toLocaleString(...) part is OK, the rest is not.
I
Ilmari Karonen

For moment.js users, you can now use moment-timezone. Using it, your function would look something like this:

function toTimeZone(time, zone) {
    var format = 'YYYY/MM/DD HH:mm:ss ZZ';
    return moment(time, format).tz(zone).format(format);
}

I wasn't sure how to add new timezones, the docs didn't help me. I'm just a programmer, not a time expert!
The problem here is that this does not return a new Date object, it returns a string. If that's what you want that's good, of course.
Isn't it "return moment(time).tz(zone).format(format);" ? The one you gave in your code have me "Invalid Date" error.
It is not possible to load Moment.js in the browser. Very sad :(
If you're not happy about sending 180K to the browser with a copy of the tz database and can live with degradation to the current timezone on older browsers, try out @lambinator's answer using Date.prototype.toLocaleString.
F
Flimm

Most browsers support the toLocaleString function with arguments, older browsers usually ignore the arguments.

const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' }); console.log(str);


Edge and chrome liked it:)
It worked just now on Chrome v59 and Firefox desktop v54 and Chome on Android v59 and Safari 10 on iOS 10.3. It didn't work on IE10. MDN's description of Date.prototype.toLocaleString() has a toLocaleStringSupportsLocales() implementation that allows you to reliably check for support.
Also, in all the browsers above, they format exactly the same as shown in jsfiddle.net/pmorch/ptqwmbyu
Successfully tested in node.js v8.7.0
No, this starts from the current time, but the question is about converting an arbitrary time (& tz) and these are very different - Date just picks up the current system time with no way to override it.
J
Jörn Berkefeld

Stolen shamelessly from: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329

/** 
 * function to calculate local time
 * in a different city
 * given the city's UTC offset
 */
function calcTime(city, offset) {

    // create Date object for current location
    var d = new Date();
   
    // get UTC time in msec
    var utc = d.getTime();
   
    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));
   
    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();
}

this function is useful to calculate time zone value by providing name of a city/country and offset value


nice....but I think he wants the offset to be looked up for him based on the passed in city.
This doesn't take into account daylight savings changes.
doesn't answer the question but answers mine (+1)
That '3600000' literally killed me! In the input, tz should be given in hours! And, it should be subtracted. So, if you pass: var d=new Date calcTime('', d.getTimezoneOffset() / 60 ); It should give back the same time.
This answer is seriously out of date and should be removed, particularly the part using toLocaleString, which will likely report the host timezone when it has been shifted to a different timezone. There are much better ways of manually creating timestamps for different offsets.
m
mplungjan

Okay, found it!

I'm using timezone-js. this is the code:

var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
dt.setTimezone("Asia/Jakarta");

console.debug(dt); //return formatted date-time in asia/jakarta

I have to vote against this, timezone-js does not support DST and it does not advertise that in its readme, which makes it a bad tip for people looking for this. See: github.com/mde/timezone-js/issues/51 and a number of other issues that have been filed and that don't seem to get fixed.
@nus yeah, but there really is not a solution for client side timezone/date management... jquery ui datepicker has been driving me crazy because of this. cheers
@Marabunta, looks like moment-timezone(answer by Brian Di Palma) supports DST github.com/moment/moment-timezone/issues/21
Don't use TimezoneJS, it's bugged around DST changes.
E
Endless

If you don't want to import some big library you could just use Intl.DateTimeFormat to convert Date objects to different timezones.

// Specifying timeZone is what causes the conversion, the rest is just formatting const options = { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZone: 'Asia/Jakarta', timeZoneName: 'short' } const formatter = new Intl.DateTimeFormat('sv-SE', options) const startingDate = new Date("2012/04/10 10:10:30 +0000") const dateInNewTimezone = formatter.format(startingDate) console.log(dateInNewTimezone) // 12-04-10 17:10:30 GMT+7

Offsets, daylight saving, and changes in the past will be taken care of for you.


IE10+ doesn't support Intl API for time zones. moment.github.io/luxon/docs/manual/matrix.html
This is actually the best answer. toLocaleString has inconsistent implementation, and this works from IE11 onward.
FYI: This actually does not work in IE11, at least on Windows 8.1. When you try to create the formatter object, you get: ``` Option value 'Asia/Jakarta' for 'timeZone' is outside of valid range. Expected: ['UTC'] ```
is there a way to convert the final result from the formatter into a Date object again?
This worked out great for my needs. As far as support goes, if IE isn't a requirement, it's at 96%, so for me that was good enough. @mding5692 use new Date(Date.parse(new Intl.DateTimeFormat(...))), though note that Date.parse is ES5 and up only.
F
Fudge

Got it!

Wanted to force the date shown = server date, no mattter the local settings (UTC).

My server is GMT-6 --> new Date().getTimezoneOffset() = 360

myTZO = 360;
myNewDate = new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);

Although it shows the correct naive time, the timezone information from myOldDateObj is kept. So actually it is the wrong time (when you take time as an instance in time and not the time on a watch).
@gabn88 : You won't be able to change the server time using Javascript... To fix the server time, do it at operating system level.
I don't need to fix server time ;) Server time is always UTC for me. But I have different organisation in different timezones. And their devices should always show the time of where their organisation is stationed, wherever they are.
We hava similar problem of showing dates always X timezone. We try to send all the dates in string format from server and in the browser we just treat them as local timezone dates.
Is there a reliable way to get the offset, where it considers daylight savings?
C
Codemaker

You can use to toLocaleString() method for setting the timezone.

new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })

For India you can use "Indian/Christmas" and the following are the various timeZones,

"Antarctica/Davis",
    "Asia/Bangkok",
    "Asia/Hovd",
    "Asia/Jakarta",
    "Asia/Phnom_Penh",
    "Asia/Pontianak",
    "Asia/Saigon",
    "Asia/Vientiane",
    "Etc/GMT-7",
    "Indian/Christmas"

You aren't setting the timeZone, but rather producing a string with the time expressed in that timeZone. The date stays the same.
The toLocaleString solution was already given 4 years ago.
"Etc/GMT-7" - is a very useful value.
India/Christmas is the time zone identifier for Christmas Island (an Australian territory located in the Indian Ocean). For India, the preferred time zone identifier is Asia/Kolkata.
s
seeking27

I should note that I am restricted with respect to which external libraries that I can use. moment.js and timezone-js were NOT an option for me.

The js date object that I have is in UTC. I needed to get the date AND time from this date in a specific timezone('America/Chicago' in my case).

 var currentUtcTime = new Date(); // This is in UTC

 // Converts the UTC time to a locale specific format, including adjusting for timezone.
 var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));

 console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
 console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
 console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
 console.log('currentDateTimeCentralTimeZone: ' +        currentDateTimeCentralTimeZone.toLocaleDateString());
 console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
 console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());

UTC is currently 6 hours ahead of 'America/Chicago'. Output is:

currentUtcTime: 11/25/2016
currentUtcTime Hour: 16
currentUtcTime Minute: 15

currentDateTimeCentralTimeZone: 11/25/2016
currentDateTimeCentralTimeZone Hour: 10
currentDateTimeCentralTimeZone Minute: 15

new Date(); return local timezone, not UTC
from the docs: If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.
Hmm. Kinda confusing. This doesn't change the timezone on a date; rather it creates a new date with the changed hours. It would be much clearer to use a regular expression to extract the values you want from the string that is created from the toLocaleString call.
Seems unreliable. This might work for users in US Central time, with their browsers set to a US locale, but it will break in other places when daylight savings start or finish (because the time change will be at a different time), and at least some JS interpreters parse date strings using the machine-set locale.
S
Santiago Corredoira

If you just need to convert timezones I have uploaded a stripped-down version of moment-timezone with just the bare minimum functionallity. Its ~1KB + data:

S.loadData({
    "zones": [
        "Europe/Paris|CET CEST|-10 -20|01010101010101010101010|1GNB0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0|11e6",
        "Australia/Sydney|AEDT AEST|-b0 -a0|01010101010101010101010|1GQg0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0|40e5",
    ],
    "links": [
        "Europe/Paris|Europe/Madrid",
    ]
});

let d = new Date();
console.log(S.tz(d, "Europe/Madrid").toLocaleString());
console.log(S.tz(d, "Australia/Sydney").toLocaleString());

This is a time bomb… it will break when daylight savings rules change, which happens all the time.
@michael-scheper of course you need to keep the zones data up to date.
D
DarkSuniuM

Here is my code, it is working perfectly, you can try with give below demo:

$(document).ready(function() { //EST setInterval( function() { var estTime = new Date(); var currentDateTimeCentralTimeZone = new Date(estTime.toLocaleString('en-US', { timeZone: 'America/Chicago' })); var seconds = currentDateTimeCentralTimeZone.getSeconds(); var minutes = currentDateTimeCentralTimeZone.getMinutes(); var hours = currentDateTimeCentralTimeZone.getHours()+1;//new Date().getHours(); var am_pm = currentDateTimeCentralTimeZone.getHours() >= 12 ? "PM" : "AM"; if (hours < 10){ hours = "0" + hours; } if (minutes < 10){ minutes = "0" + minutes; } if (seconds < 10){ seconds = "0" + seconds; } var mid='PM'; if(hours==0){ //At 00 hours we need to show 12 am hours=12; } else if(hours>12) { hours=hours%12; mid='AM'; } var x3 = hours+':'+minutes+':'+seconds +' '+am_pm // Add a leading zero to seconds value $("#sec").html(x3); },1000); });


Welcome to StackOverflow! Can u provide more information like how this code works and what it does? How it fixes the problem?
My given above code is to update your timezone to other countries timezone.
You need to put the HTML in your html file and given above jquery code need to be in the footer. It will work for you as per ('en-US', { timeZone: 'America/Chicago' }) you need to update these two values, if you want other countries timezone Thanks
No wait. I just upvoted this without looking carefully. Why are you adding 1 to currentDateTimeCentralTimeZone.getHours() ? Without that it would work and is the same as seeking27's answer stackoverflow.com/a/40809160/1404185
'It is working perfectly'—are you sure? Have you tested it in multiple time zones, at different times of year (thus with different daylight savings rules), in different locales (including the default US locale, with its confusing date format)? I've definitely met JS interpreters that use the system locale when parsing new Date(string), so forcing an AM/PM time and US-formatted date is asking for trouble IMHO.
F
Fudge

Set a variable with year, month, and day separated with - symbols, plus a T and the time in HH:mm:ss pattern, followed by +01:00 at the end of the string (in my case the time zone is +1). Then use this string as the argument for the date constructor.

// desired format: 2001-02-04T08:16:32+01:00
dateAndTime = year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00+01:00";

var date = new Date(dateAndTime );

S
Sandeep Chowdary

You can also use https://www.npmjs.com/package/ctoc_timezone

It has got much simple implementation and format customisation.

Changing format in toTimeZone:

CtoC.toTimeZone(new Date(),"EST","Do MMM YYYY hh:mm:ss #{EST}");

Output :

28th Feb 2013 19:00:00 EST

You can explore multiple functionalities in the doc.


R
Rahul Mankar

You can try this also for convert date timezone to India:

var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
var indainDateObj = new Date(indianTimeZoneVal);
indainDateObj.setHours(indainDateObj.getHours() + 5);
indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);
console.log(indainDateObj);

after the 2nd step itself i get the time in India... so why are you still adding 5&1/2hrs to it?
When using that method I get the following here in Norway when I console log with Chrome: Original: Thu Sep 27 2018 15:53:46 GMT+0200 (sentraleuropeisk sommertid). Modified: Thu Sep 27 2018 19:23:46 GMT+0200 (sentraleuropeisk sommertid). “sentraleuropeisk sommertid” means Central European Summer Time. Not sure if that would work when you need summer time for India, or vice versa when you're in India and need summer time for Europe, and so on.
Using setHours() like this does not account for day, month, year transitions, for example 3:30 am in New Dell on the 8th is 11 pm on the 7th in London. Then consider the end of the month, year and leap days. Have Date do that math
 let local_time = new Date(zulu_time.getTime() + 3600000*std_timezone.timezone_factor - 60*60*1000); let date_str = local_time.toISOString().slice(0, 10); let time_str = local_time.toISOString().slice(11, -1); let timezone_str = std_timezone.timezone_str; 
A
Alexandre Liscia

I recently did this in Typescript :

// fromTimezone example : Europe/Paris, toTimezone example: Europe/London
private calcTime( fromTimezone: string, toTimezone: string, dateFromTimezone: Date ): Date {
  const dateToGetOffset = new Date( 2018, 5, 1, 12 );

  const fromTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: fromTimezone, hour12: false } );
  const toTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: toTimezone, hour12: false } );

  const fromTimeHours: number = parseInt( fromTimeString.substr( 0, 2 ), 10 );
  const toTimeHours: number = parseInt( toTimeString.substr( 0, 2 ), 10 );

  const offset: number = fromTimeHours - toTimeHours;

  // convert to msec
  // add local time zone offset
  // get UTC time in msec
  const dateFromTimezoneUTC = Date.UTC( dateFromTimezone.getUTCFullYear(),
    dateFromTimezone.getUTCMonth(),
    dateFromTimezone.getUTCDate(),
    dateFromTimezone.getUTCHours(),
    dateFromTimezone.getUTCMinutes(),
    dateFromTimezone.getUTCSeconds(),
  );

  // create new Date object for different city
  // using supplied offset
  const dateUTC = new Date( dateFromTimezoneUTC + ( 3600000 * offset ) );

  // return time as a string
  return dateUTC;
}

I Use "en-UK" format because it is a simple one. Could have been "en-US" or whatever works.

If first argument is your locale timezone and seconde is your target timezone it returns a Date object with the correct offset.


o
omarjebari

Having looked around a lot including links from this page i found this great article, using moment timezone:

https://www.webniraj.com/2016/11/23/javascript-using-moment-js-to-display-dates-times-in-users-timezone/

To summarise it:

Get the user's timezone

var tz = moment.tz.guess();
console.info('Timezone: ' + tz);

Returns eg: Timezone: Europe/London

Set the default user timezone

moment.tz.setDefault(tz);

Set custom timezone

moment.tz.setDefault('America/Los_Angeles');

Convert date / time to local timezone, assumes original date/time is in UTC

moment.utc('2016-12-25 07:00').tz(tz).format('ddd, Do MMMM YYYY, h:mma');

Returns: Sun, 25th December 2016, 7:00am

Convert date/time to LA Time

moment.utc('2016-12-25 07:00').tz('America/Los_Angeles').format('ddd, Do MMMM YYYY, h:mma');

Returns: Sat, 24th December 2016, 11:00pm

Convert from LA time to London

moment.tz('2016-12-25 07:00', 'America/Los_Angeles').tz('Europe/London').format( 'ddd, Do MMMM YYYY, h:mma' );

Returns: Sun, 25th December 2016, 3:00pm


m
mhdi

Provide the desired time zone, for example "Asia/Tehran" to change the current time to that timezone. I used "Asia/Seoul".

You can use the following codes. change the style if you need to do so.

please keep in mind that if you want to have h:m:s format instead of HH:MM:SS, you'll have to remove "function kcwcheckT(i)".

function kcwcheckT(i) { if (i < 10) { i = "0" + i; } return i; } function kcwt() { var d = new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"}); d = new Date(d); var h = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); h = kcwcheckT(h); m = kcwcheckT(m); s = kcwcheckT(s); document.getElementById("kcwcurtime").innerHTML = h + ":" + m + ":" + s; var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; document.getElementById("kcwcurday").innerHTML = days[d.getDay()] } kcwt(); window.setInterval(kcwt, 1000); @import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap'); .kcwsource {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;} .kcwsource p {font-family: 'Nunito', sans-serif;} .CurTbx {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;} .kcwcstyle {font-family: 'Nunito', sans-serif; font-size: 22px;display: inline-block;} .kcwcurstinf {font-family: 'Nunito', sans-serif; font-size: 18px;display: inline-block;margin: 0;} .kcwcurday {margin: 0;} .kcwcurst {margin: 0 10px 0 5px;} /*Using the css below you can make your style responsive!*/ @media (max-width: 600px){ .kcwcstyle {font-size: 14px;} .kcwcurstinf {font-size: 12px;} }

This Pen was originally developed for KOCOWAFA.com

(Seoul, Korea)


M
Muhammad

Do it as easy:

const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; console.log(timeZone); var d = new Date(); console.log(d.toLocaleString('en-US', { timeZone }));


The trouble with this is that the output is a String, and JavaScript doesn't seem to provide an elegant, 'as easy' way to convert from a String to a timezone-naïve Date, without the potential of getting messed up by locale and daylight savings issues.
G
Gerson Diniz

Using luxon library:

import { DateTime } from "luxon";

// Convert function:
const convertTz = (datetime, fromTz, toTz, format='yyyy-MM-dd HH:mm:ss') => {
  return DateTime.fromFormat(datetime, format, { zone: fromTz }).setZone(toTz).toFormat(format);
}

// Use it like this:
console.log(convertTz('2021-10-03 19:00:00', 'Europe/Lisbon', 'America/New_York'));


R
RobG

I don't know an easy method to convert a date object to any time zone, but if you want to convert it to the local time zone, you can just convert it with Date.prototype.getTime() to the corresponding number of milliseconds, and back again.

let date0 = new Date('2016-05-24T13:07:20'); let date1 = new Date(date0.getTime()); console.log(`${date0}\n${date1}`);

For example, date.getHours() will now return 15 instead of 13 if you are, like me, in Austria (and it's summer).

I've read that the various datetime functions may exhibit non-standard behaviour in some browsers, so test this first. I can confirm that it works in Chrome.


Why was this voted down? This is by far the easiest and best way of doing this. Most of the answers above do not take summer/winter time into consideration
What's the point of the second line? The Date constructor assumes your local time zone already. Both of these lines returns a date in the local browser time zone, and doesn't answer the question on how to convert to another time zone with daylight savings time.
This answer is pointless. The initial string should be parsed as local, so the first statement will create a Date with a time value that is equivalent to 2016-05-24T13:07:20 in the host timezone. The second line just copies that Date. How it could be upvoted at all is a mystery.
g
goat

People familiar with the java 8 java.time package, or joda-time will probably love the new kid on the block: the js-joda library.

Install

npm install js-joda js-joda-timezone --save

Example

<script src="node_modules/js-joda/dist/js-joda.js"></script>
<script src="node_modules/js-joda-timezone/dist/js-joda-timezone.js"></script>
<script>
var dateStr = '2012/04/10 10:10:30 +0000';
JSJoda.use(JSJodaTimezone);
var j = JSJoda;
// https://js-joda.github.io/js-joda/esdoc/class/src/format/DateTimeFormatter.js~DateTimeFormatter.html#static-method-of-pattern
var zonedDateTime = j.ZonedDateTime.parse(dateStr, j.DateTimeFormatter.ofPattern('yyyy/MM/dd HH:mm:ss xx'));
var adjustedZonedDateTime = zonedDateTime.withZoneSameInstant(j.ZoneId.of('America/New_York'));
console.log(zonedDateTime.toString(), '=>', adjustedZonedDateTime.toString());
// 2012-04-10T10:10:30Z => 2012-04-10T06:10:30-04:00[America/New_York]
</script>

In true java nature, it's pretty verbose lol. But, being a ported java library, especially considering they ported 1800'ish test cases, it also probably works superbly accurately.

Chrono manipulation is hard. That's why many other libraries are buggy in edge cases. Moment.js seems to get timezones right, but the other js libs I've seen, including timezone-js, don't seem trustworthy.


A
Ashish Ranjan

I was having trouble using Moment Timezone. I am adding this answer just so if somebody else faces the same issue. So I have a date string 2018-06-14 13:51:00 coming from my API. I know that this is stored in UTC but the string doesn't speak for itself.

I let moment timezone know, what timezone this date is from by doing:

let uTCDatetime = momentTz.tz("2018-06-14 13:51:00", "UTC").format();
// If your datetime is from any other timezone then add that instead of "UTC"
// this actually makes the date as : 2018-06-14T13:51:00Z

Now I would like to convert it to a specific timezone by doing:

let dateInMyTimeZone = momentTz.tz(uTCDatetime, "Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss");
// now this results into: 2018-06-14 19:21:00, which is the corresponding date in my timezone.

M
Muhammad Azeem

Just set your desire country timezone and You can easily show in html it update using SetInteval() function after every one minut. function formatAMPM() manage 12 hour format and AM/PM time display.

$(document).ready(function(){
        var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
        pakTime = new Date(pakTime);

        var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
        libyaTime = new Date(libyaTime);



         document.getElementById("pak").innerHTML = "PAK  "+formatAMPM(pakTime);
         document.getElementById("ly").innerHTML = "LY   " +formatAMPM(libyaTime);

        setInterval(function(today) {
            var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
            pakTime = new Date(pakTime);

            var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
            libyaTime = new Date(libyaTime);


           document.getElementById("pak").innerHTML = "PAK  "+formatAMPM(pakTime);
           document.getElementById("ly").innerHTML = "LY  " +formatAMPM(libyaTime);

        },10000);

         function formatAMPM(date) {
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var ampm = hours >= 12 ? 'pm' : 'am';
            hours = hours % 12;
            hours = hours ? hours : 12; // the hour '0' should be '12'
            minutes = minutes < 10 ? '0'+minutes : minutes;
            var strTime = hours + ':' + minutes + ' ' + ampm;
            return strTime;
        }


    });

Z
Zubair Rizwan

there is server issue pick gmt+0000 standard time zone you can change it by using library moment-timezone in javascript

const moment = require("moment-timezone")
const dateNew = new Date()
const changeZone = moment(dateNew);
changeZone.tz("Asia/Karachi").format("ha z");
// here you can paste "your time zone string"

J
John

A bit redundant with all these answers, but this worked for me for getting the current Date object with a specific hourly offset.

function hourToMs(hour) { return hour * 60 * 1000 * 60; } function minToMs(min) { return min * 60 * 1000; } function getCurrentDateByOffset(offset) { // Get the current timezone in milliseconds to reset back to GMT aka +0 let timezoneOffset = minToMs((new Date()).getTimezoneOffset()); // get the desired offset in milliseconds, invert the value because javascript is dum let desiredOffset = hourToMs(offset * -1); return new Date(Date.now() + timezoneOffset - desiredOffset); } // -6 hours is central timezone console.log("The time is: " + getCurrentDateByOffset(-6));


F
Fudge

There is an npm module called timezones.json you can use for this. It basically consists of a json file with objects containing information on daylight savings and offset.

For asia/jakarta, it would be able to return this object:

{
  "value": "SE Asia Standard Time",
  "abbr": "SAST",
  "offset": 7,
  "isdst": false,
  "text": "(UTC+07:00) Bangkok, Hanoi, Jakarta",
  "utc": [
    "Antarctica/Davis",
    "Asia/Bangkok",
    "Asia/Hovd",
    "Asia/Jakarta",
    "Asia/Phnom_Penh",
    "Asia/Pontianak",
    "Asia/Saigon",
    "Asia/Vientiane",
    "Etc/GMT-7",
    "Indian/Christmas"
  ]
}

You can find it here:

https://github.com/dmfilipenko/timezones.json

https://www.npmjs.com/package/timezones.json

hope it's useful


A
Amir

This is worked for me in React Native Application.

import moment from 'moment-timezone'

function convertTZ(date, tzString) {
  const formatedDate = moment(date).tz(tzString).format()
  return formatedDate
}

export {convertTZ}

L
Lee

This should work for everyone. You can test out different time zones by changing the time manually on your machine. This function will adapt accordingly.

 function getCurrentTime() {
     const d = new Date() //2022-07-22T16:27:21.322Z
     const t = d.getTime(); //d in milliseconds 1658507241322
     const offset = -d.getTimezoneOffset()/60 //current offset in hours -4
     const curretMilli = t + (offset * 3600000) //cuuret local time milliseconds need to convert offset to milliseconds
     return new Date(curretMilli) //converts current local time in milliseconds to a Date //2022-07-22T12:27:21.322Z
 }

a
anthony

Time Zone Offset for your current timezone

date +%s -d '1 Jan 1970'

For my GMT+10 timezone (Australia) it returned -36000


J
Jerry

quick and dirty manual hour changer and return:

return new Date(new Date().setHours(new Date().getHours()+3)).getHours()

too dirty (and too messy)