JavaScript:使用时区将UTC时间转换为本地时间 [英] JavaScript: Convert UTC time to local time using timezone

查看:455
本文介绍了JavaScript:使用时区将UTC时间转换为本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有UTC日期时间字符串和时区名称。我从第三方API获取此信息。我需要使用JavaScript / NodeJS将UTC时间转换为该时区的本地时间,并获取该时区的当前时间。有没有相同的库/方法?

I have a UTC date time string and time zone name. I am getting this from a third party API. I need to convert the UTC time to local time of that timezone using JavaScript/NodeJS as well as get that time zone's current time. Is there any library/method available for the same?

var timezone = "America/New_York";//This will always be in Olson format.
var UTCTime = "2017-09-03T02:00:00Z";
var localTime; //I need to find the equivalent of UTCTime for America/New_York
var currentTime; //Current time of time zone America/New_York


推荐答案

这可以通过以下几种方式完成:

This can be done in few ways:

var options = {
    timeZone: "America/New_York",
    year: 'numeric', month: 'numeric', day: 'numeric',
    hour: 'numeric', minute: 'numeric', second: 'numeric'
};

var formatter = new Intl.DateTimeFormat([], options);

var UTCTime = "2017-09-03T02:00:00Z";
var localTime = formatter.format(new Date(UTCTime));
var currentTime = formatter.format(new Date()); console.log(currentTime, localTime);

或者你可以使用 moment.js 库。

这篇关于JavaScript:使用时区将UTC时间转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆