根据时区用户转换日期

时间:2019-04-24 19:12:12

标签: javascript timezone

我有一个要根据其时区进行转换的日期。

例如,我想将其设置为美国东部时间(美国/纽约)

2019-04-24 12:00:00

,并且如果用户从America / Los_Angeles浏览该网站,则会显示:

2019-04-24 09:00:00

我需要能够返回小时,因此在该示例中:9。

我尝试使用https://github.com/iansinnott/jstz来确定其时区和https://moment.github.io/luxon,以期在没有任何运气的情况下进行转换。

我正在通过更改计算机时区(没有任何运气)进行测试。

5 个答案:

答案 0 :(得分:0)

您可以保留一份时琴酮标识符列表,以及与您当地时间相对应的+/-小时数列表(由您的时间函数返回)。

一旦有了用户的时区,并且已经从本地时间戳中提取了当前时间,只需在列表中查找时区并使用它的索引来访问第二个列表,以查找要从中添加或减去多少小时。用户时间。

答案 1 :(得分:0)

{{3}}

var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));

// toLocaleString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleString());
// → "12/11/2012, 7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles

或者您可以使用getYeargetMonthgetDategetHoursgetMinutesgetSeconds来格式化自己的日期表示形式。这些方法都根据用户的本地时区返回值。

答案 2 :(得分:0)

可以像这样根据时间转换日期。参考convert date to another time zone示例片段在下面。

var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});
usaTime = new Date(usaTime);
console.log('USA time: '+usaTime.toLocaleString())


var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/Los_Angeles"});
usaTime = new Date(usaTime);
console.log('USA time: '+usaTime.toLocaleString())

答案 3 :(得分:0)

听起来好像您是在要求将转换为用户的本地时区(无论是什么时候)。您不需要为此进行时区检测,但是目前 do 需要一个库。 (建议将toLocaleString与时区参数一起使用的答案是不正确的,因为该函数会将转换为到特定的时区,但是不能向另一个方向移动。)

自从您提到Luxon以来,我将提供一个针对Luxon的答案:

luxon.DateTime.fromFormat('2019-04-24 12:00:00',       // the input string
                          'yyyy-MM-dd HH:mm:ss',       // the format of the input string
                          { zone: 'America/New_York'}) // the time zone of the input
              .toLocal()                               // convert to the user's local time
              .toFormat('yyyy-MM-dd HH:mm:ss')         // return a string in the same format

//=>  "2019-04-24 09:00:00"

其他库(例如date-fns-timezonejs-JodaMoment-Timezone)也提供了此功能,但JavaScript尚未内置该功能。

答案 4 :(得分:0)

我认为这个问题可能需要进一步澄清-我的第一印象是您指的是您已经拥有并从服务器提供服务的日期时间。这个问题是否归结为 Date 对象具有“用户时区意识”?或不?但这是(确切地说是一些方法)

您的日期/时间是美国东部时间2019-04-24 12:00:00(我假设是下午) 这表示Unix时间戳以毫秒为单位1556121600000 (我假设4月是白天,所以不是纯EST,而是EDT和UTC-4:00的偏移量)

致电时

console.log(new Date(1556121600000).getHours())

对于在美国/洛杉矶太平洋时间带有PDT时区的浏览器中执行的Javascript,这是否不像您建议的那样返回9?

根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours的建议:

  

getHours()方法返回指定日期的小时,   根据当地时间。

相关问题