Convert date to another timezone in JavaScript

2018-12-31 01:32发布

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?

20条回答
不流泪的眼
2楼-- · 2018-12-31 01:35

If the format isn't super important and you don't want import some big library you could just use Intl.DateTimeFormat to convert Date objects to different timezones.

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 formater = new Intl.DateTimeFormat('sv-SE', options)
const date = new Date("2012/04/10 10:10:30 +0000")

console.log(formater.format(date))

Offsets, daylight saving, and other diff changed in the past will be taken care of for you

You can experiment with the language to get other literals.

查看更多
不再属于我。
3楼-- · 2018-12-31 01:38

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>

查看更多
深知你不懂我心
4楼-- · 2018-12-31 01:39

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.

查看更多
泪湿衣
5楼-- · 2018-12-31 01:41

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());
查看更多
柔情千种
6楼-- · 2018-12-31 01:42

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);
}
查看更多
初与友歌
7楼-- · 2018-12-31 01:44

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.
查看更多
登录 后发表回答