【问题标题】:How to convert from date.now to pacific time如何从 date.now 转换为太平洋时间
【发布时间】:2020-11-26 04:13:41
【问题描述】:

在我当前的项目中,我必须为每个用户实现经过时间并将其显示在网页上。 但是,使用 date.now 将返回 UTC,我想在太平洋时间得到它。我在网上搜索和研究,但无法让它工作......有没有办法将UTC时间转换为太平洋时间?

【问题讨论】:

  • 试试这个:'var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});',别忘了更改时区。
  • 打算在太平洋打发时间没问题。为了保持一致,假设所有计算都在UTC 中,最后使用toLocaleDateString 进行显示。您的所有代码都将以这种方式直观。

标签: javascript html node.js reactjs


【解决方案1】:

我看到你手头有几个选项。

选项 1 - 使用外部库(moment / date-fns)

如果您的应用将严重依赖时区、日期等,请考虑使用这些库。

例如:

moment.tz(12345678, "America/Los_Angeles") // 12345678 being your Date timestamp

在此处查看更多信息:

date-fns moment

选项 2 - 你需要使用 vanilla JS

this thread 上找到了一些答案,但我看不出它们中的任何一个是长期可靠的(因为节省时间等) - 我可能错了,但我求助于日期/时间库我的应用大量使用相同的。

【讨论】:

  • 谢谢安东尼奥,我会看看上面的链接!
【解决方案2】:

你可以这样做:

const event = new Date(Date.now());

const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

console.log(event.toLocaleDateString('us-PT', options));
其中“us”是“美国”,“PT”是“太平洋时间” 要查看更多信息,请访问 MDN web docs Date.prototype.toLocaleDateString()

【讨论】:

  • 谢谢丹尼尔,我去看看!!
【解决方案3】:

这对我有用。

const date = new Date().toLocaleDateString('en-US', { timeZone: 'America/Los_Angeles' });
const time = new Date().toLocaleTimeString('en-US', { timeZone: 'America/Los_Angeles' });
const datetime = new Date().toLocaleString('en-US', { timeZone: 'America/Los_Angeles' });

希望它可以帮助其他人节省时间。

【讨论】:

    猜你喜欢
    • 2011-03-13
    • 2021-03-02
    • 2018-04-25
    • 2012-12-08
    • 2014-11-25
    • 2018-09-15
    • 2021-09-05
    • 2015-01-22
    • 1970-01-01
    相关资源
    最近更新 更多