admin管理员组文章数量:1125803
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 .tab
Is there an easy way to do this?
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?
Share Improve this question edited Apr 10, 2015 at 14:12 AstroCB 12.4k20 gold badges58 silver badges74 bronze badges asked Apr 10, 2012 at 11:25 Rizky RamadhanRizky Ramadhan 7,7604 gold badges29 silver badges33 bronze badges 6- 1 Find the UTC offset of a given city. stackoverflow.com/questions/3002910/… – Brandon J. Boone Commented Apr 10, 2012 at 12:05
- 6 I want to to calculate not just the UTC offset but also Daylight saving/summer time. So the time will return correctly. – Rizky Ramadhan Commented Apr 10, 2012 at 12:11
- possible duplicate of How to initialize javascript date to a particular timezone – Matt Johnson-Pint Commented Aug 7, 2014 at 18:28
- Check this one as well stackoverflow.com/questions/16084313/… – Amol M Kulkarni Commented Sep 28, 2015 at 13:09
- Off set of your time zone using unix date command: date +%s -d '1 Jan 1970' – anthony Commented Feb 15, 2018 at 5:06
37 Answers
Reset to default 1 2 Next 456Here 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.
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);
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);
}
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
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
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.
UPDATE
There is also this new Temporal tool that handles timezones among other things. Like only dates or only time. It's experimental as of now
It's meant to replace the old legacy Date
var isoDate = new Date().toJSON() // eg: '2022-11-18T13:56:09.697Z'
Temporal.Instant.from(isoDate).toZonedDateTimeISO('Europe/Stockholm')
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);
A simple, functional, and cross-browser solution for converting between time zones and converting a date to a string with a selected time zone:
export function convertTimeZone(
date: Date,
timeZoneFrom?: string | null, // default timezone is Local
timeZoneTo?: string | null, // default timezone is Local
): Date {
const dateFrom = timeZoneFrom == null
? date
: new Date(
date.toLocaleString('en-US', {
timeZone: timeZoneFrom,
}),
)
const dateTo = timeZoneTo == null
? date
: new Date(
date.toLocaleString('en-US', {
timeZone: timeZoneTo,
}),
)
const result = new Date(date.getTime() + dateTo.getTime() - dateFrom.getTime())
return result
}
export function dateToString(date: Date, timeZone: string): string {
date = convertTimeZone(date, 'UTC', timeZone)
const year = date.getUTCFullYear().toString().padStart(4, '0')
const month = (date.getUTCMonth() + 1).toString().padStart(2, '0')
const day = date.getUTCDate().toString().padStart(2, '0')
const hours = date.getUTCHours().toString().padStart(2, '0')
const minutes = date.getUTCMinutes().toString().padStart(2, '0')
const seconds = date.getUTCSeconds().toString().padStart(2, '0')
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
Tests
describe('date', function () {
it('convertTimeZone', function () {
// UTC => UTC
expect(convertTimeZone(new Date('2020-01-01T00:00:00.000Z'), 'UTC', 'UTC'))
.toEqual(new Date('2020-01-01T00:00:00.000Z'))
// UTC => Europe/Kiev
expect(convertTimeZone(new Date('2020-01-01T00:00:00.000Z'), 'UTC', 'Europe/Kiev'))
.toEqual(new Date('2020-01-01T02:00:00.000Z'))
// Europe/Kiev => UTC
expect(convertTimeZone(new Date('2020-01-01T00:00:00.000Z'), 'Europe/Kiev', 'UTC'))
.toEqual(new Date('2019-12-31T22:00:00.000Z'))
// Europe/Kiev => America/Los_Angeles
expect(convertTimeZone(new Date('2020-01-01T00:00:00.000Z'), 'Europe/Kiev', 'America/Los_Angeles'))
.toEqual(new Date('2019-12-31T14:00:00.000Z'))
// America/Los_Angeles => Europe/Kiev
expect(convertTimeZone(new Date('2020-01-01T00:00:00.000Z'), 'America/Los_Angeles', 'Europe/Kiev'))
.toEqual(new Date('2020-01-01T10:00:00.000Z'))
// Local => Local
expect(convertTimeZone(new Date('2020-01-01T00:00:00.000Z'), null, null))
.toEqual(new Date('2020-01-01T00:00:00.000Z'))
// forward and backward for timezone list
const timeZones = [
null, // Local
'UTC',
'Europe/Kiev',
'America/Los_Angeles',
'America/New_York',
'America/Chicago',
'America/Denver',
'Europe/London',
'Europe/Paris',
'Europe/Moscow',
'Europe/Berlin',
'Asia/Tokyo',
'Asia/Shanghai',
'Asia/Hong_Kong',
'Asia/Kolkata',
'Australia/Sydney',
'Australia/Melbourne',
'Australia/Perth',
'Australia/Brisbane',
]
for (const timeZoneFrom of timeZones) {
for (const timeZoneTo of timeZones) {
const date = new Date('2020-01-01T00:00:00.000Z')
const result = convertTimeZone(date, timeZoneFrom, timeZoneTo)
const resultBack = convertTimeZone(result, timeZoneTo, timeZoneFrom)
expect(resultBack).toEqual(date)
}
}
})
it('dateToString', function () {
expect(dateToString(new Date('2020-01-01T00:00:00.000Z'), 'UTC'))
.toEqual('2020-01-01 00:00:00')
expect(dateToString(new Date('2020-01-01T00:00:00.000Z'), 'Europe/Kiev'))
.toEqual('2020-01-01 02:00:00')
expect(dateToString(new Date('2020-01-01T00:00:00.000Z'), 'America/Los_Angeles'))
.toEqual('2019-12-31 16:00:00')
expect(dateToString(new Date('2020-01-01T00:00:00.000Z'), 'America/New_York'))
.toEqual('2019-12-31 19:00:00')
})
it('dateToString current', function () {
console.log(`Current date UTC: ${dateToString(new Date(), 'UTC')}`)
console.log(`Current date Europe/Kiev: ${dateToString(new Date(), 'Europe/Kiev')}`)
console.log(`Current date America/Los_Angeles: ${dateToString(new Date(), 'America/Los_Angeles')}`)
})
})
You can use to toLocaleString() method for setting the timezone.
new Date().toLocaleString('en-US', { timeZone: 'Asia/Kolkata' })
For India you can use "Asia/Kolkata" 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"
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'));
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
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());
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);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p class="date_time"><strong id="sec"></strong></p>
</body>
</html>
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 );
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.
Do it as easy:
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timeZone);
var d = new Date();
console.log(d.toLocaleString('en-US', { timeZone }));
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);
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.
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
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;}
}
<div class="kcwsource"><p>This Pen was originally developed for <a href="http://kocowafa.com" target="_blank">KOCOWAFA.com</a></p></div>
<div class="CurTbx"><p class="kcwcurst kcwcstyle" id="kcwcurday"></p><p class="kcwcurst kcwcstyle" id="kcwcurtime"></p><p class="kcwcurstinf">(Seoul, Korea)</p></div>
This is UTC date; converting UTC to IST timezone;
let sampleArray = [
{
date: "2022-12-22T19:16:26.803"
},
{
date: "2022-12-22T19:16:26.77"
},
{
date: "2022-12-22T19:16:26.737"
},
{
date: "2022-12-22T19:16:26.72"
}
];
// Get all the results whose boolresult is 'true'
// solution 1
sampleArray.map((element) => {
let utcDate = new Date(element.date).getTime();
let dateIST = new Date(utcDate);
dateIST.setHours(dateIST.getHours() + 5);
dateIST.setMinutes(dateIST.getMinutes() + 30);
element.date = dateIST;
});
console.log("Result ==>>", sampleArray);
// solution 2
sampleArray.map((element) => {
element.date = new Date(element.date).toLocaleString("en-US", {
timeZone: "Asia/Kolkata"
});
});
console.log("Result 2==>>", sampleArray);
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.
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.
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;
}
});
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"
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));
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
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}
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.
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
}
本文标签: Convert date to another timezone in JavaScriptStack Overflow
版权声明:本文标题:Convert date to another timezone in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736672714a1947008.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论