【问题标题】:How to change a date's timezone to the local timezone in Javascript? [duplicate]如何在Javascript中将日期的时区更改为本地时区? [复制]
【发布时间】:2017-09-18 10:50:18
【问题描述】:

我当前的日期是Mon Jul 03 2017 10:17:40 GMT+0530(印度标准时间)。

我想将此日期转换为特定的时区和区域设置,具体取决于用户,例如,GMT+00:00

如何将给定的日期转换为用户特定的格式?

【问题讨论】:

  • moment.js
  • 是的,我正在使用 moment.js。即moment(d).format(format) 但如何将其转换为用户特定的时区格式。就我而言,目标格式不固定。
  • @krish——你不需要做任何事情来将日期转换为用户的时区,内置的 Date.prototype.toString 将使用主机设置来生成合适的字符串。

标签: javascript date


【解决方案1】:

您可以使用Moment.js' localized formats 显示日期,具体取决于区域设置。
要检测当前用户区域设置,请参阅this question

请注意,您必须手动加载语言环境或使用内置语言环境的发布版本(moment-with-locales.js on the homepage)。

鉴于你上面的例子:

const locale = window.navigator.userLanguage || window.navigator.language
moment.locale(locale)
console.log('locale: ' + moment.locale())

const format = 'LLLL ZZ'
console.log(moment().format(format))
<script src="https://cdn.rawgit.com/moment/moment/b8a7fc31/min/moment-with-locales.min.js"></script>

【讨论】:

  • language 不是 locale,它是一种语言。
【解决方案2】:

Momentjs 时区文档中有很多示例。

moment.tz('America/Los_Angeles').format('z')  // "PDT"     (abbreviation)
moment.tz('Asia/Magadan').format('z')         // "+11"     (3-char offset)
moment.tz('Asia/Colombo').format('z')         // "+0530"   (5-char offset)

链接:

https://momentjs.com/timezone/docs/

【讨论】:

  • 感谢 hsyn ozkara。
【解决方案3】:

你可以试试这个

var date = new Date();
//getTimezoneOffset() gives difference in minutes between your timezone and GMT, multiplying it by 60*1000 converts it to milliseconds
var utc_time = new Date(date.valueOf() + date.getTimezoneOffset() * 60000);
var offset = destination_timezone_offset_in_milliseconds;
var time_in_required_timezone = new Date(utc_time.valueOf()+offset);

【讨论】:

  • 目标时区格式不固定。所以,不能使用这个解决方案。谢谢
  • 这个 javascript 在哪里运行?在您的机器或用户机器上? @krish
  • 不同的机器和不同的位置。@Shriyansh Gautam
  • 表示用户坐在不同的位置,但对于每个用户,此代码将返回他们的机器在他们的时区中的偏移量
  • 所以如果位置不同也可以工作。但是有没有办法根据单机上的时区更改日期。
猜你喜欢
  • 1970-01-01
  • 2018-03-22
  • 2023-03-16
  • 2016-09-12
  • 2020-10-09
  • 2020-05-24
  • 1970-01-01
  • 2019-09-05
  • 2020-12-28
相关资源
最近更新 更多