【问题标题】:Get current Date Object of a timezone [duplicate]获取时区的当前日期对象[重复]
【发布时间】:2019-05-24 13:42:07
【问题描述】:

在选定的时区中获取当前时间作为日期对象的最佳方法是什么。我正在使用以下代码在本机反应中获取所选时区的当前时间。

例如。 new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })

这段代码的输出是一个字符串,但我需要它在日期对象中。每次我转换回 New Date() 时,都需要默认时区,但我需要自定义时区。我也尝试使用 moment 库,而 momentTimeZone bu 无法获得正确的输出。任何人都可以帮助我解决这个问题

【问题讨论】:

    标签: javascript react-native timezone


    【解决方案1】:

    Date 也将dateString 作为参数,并且大多数字符串格式都应该有效(即Date.parse() supports):

    > now = new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })
    '12/26/2018, 3:51:28 PM'
    > now_obj = new Date(now)
    2018-12-26T14:51:28.000Z
    

    【讨论】:

    • 感谢您的回复。我的问题是我需要将从 new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' }) 获得的字符串对象转换回日期对象,而不更改日期对象的时区。 React 原生组件中的 DatepickerIOS 仅将 Date 对象作为输入。所以,我需要将字符串转换为 Date 对象。每次我将它转换回 Date 时,它​​都需要默认 timezone ,我需要保持 timeZone 不变。
    • 抱歉回复晚了。我现在知道我误解了您的用例。
    【解决方案2】:

    除非您将操作系统时区更改为您想要的,否则您似乎无法做到这一点。您可以定义函数而不是 Date 对象,如下所示:

    function getCustomDate(zone) {
        return new Date().toLocaleString('en-US', { timeZone: zone })
    }

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2016-12-23
      • 2013-06-16
      • 2019-06-05
      • 2017-11-19
      • 1970-01-01
      • 2016-12-15
      • 2014-09-08
      • 2016-07-04
      相关资源
      最近更新 更多