【问题标题】:How to convert GMT time using new Date() to AM/PM in react-native?如何在 react-native 中使用 new Date() 将 GMT 时间转换为 AM/PM?
【发布时间】:2021-06-23 05:45:07
【问题描述】:

我正在一个 react-native 项目中工作并使用矩库。我在将时间(GMT 5:30 IST)转换为 AM/PM 时遇到问题。它增加了当地时间 5:30 小时。 例如。从数据库时间下午 3:00 开始。从 new Date() => 时间转换为Wed Jun 23 2021 15:00:00 GMT+0530(印度标准时间)并在我需要的字段中。当我需要时,我再次将此 GMT 时间转换为 Am/PM。它显示的是晚上 8:30,而不是下午 3:00。

代码如下:

var scheduledDeparture = Wed Jun 23 2021 15:00:00 GMT+0530 (India Standard Time)
scheduledDeparture_Time: new Date(ScheduledDeparture), 
let finalTime = moment.utc(leavedata.scheduledDeparture_Time).format('hh:mm a').replace(/GMT.*/g,"")
console.log("finalTime ",finalTime). // 08:30PM

为什么 GMT 时间在当前时间增加 5:30 以及如何克服它?

【问题讨论】:

    标签: android reactjs react-native react-android


    【解决方案1】:

    您需要包含moment-timezone,然后您可以使用utcOffset 方法执行以下操作

    let str = '2021-06-23T15:40+01:00';
    let date = moment(str).utcOffset(str)
    console.log(date.format('DD/MM/YYYY HH:mm'))
    

    如果您正在使用Date 对象,您可以执行以下操作:

     let scheduledDeparture_Time = new Date()
     console.log(scheduledDeparture_Time.toString(), scheduledDeparture_Time.toGMTString())
     let dt2 = moment(scheduledDeparture_Time)
      console.log(dt2.format('DD/MM/YYYY HH:mm'))
    

    如果您有规定的字符串,并且无论时区如何都需要保留时间,那么只需使用substring,然后应用moment

     let scheduledDeparture ='Wed Jun 23 2021 15:00:00 GMT+0530 (India Standard Time)'
     let scheduledDeparture_Time = new Date(scheduledDeparture.substring(0, 24))
     let dt2 = moment(scheduledDeparture_Time)
      console.log(dt2.format('DD/MM/YYYY HH:mm'))
    

    fiddle

    【讨论】:

    • 下面是我的输出:scheduledDeparture_Time = Wed Jun 23 2021 15:00:00 GMT+0530 (India Standard Time) let date = moment(scheduledDeparture_Time).utcOffset(scheduledDeparture_Time) console.log(date .format('DD/MM/YYYY HH:mm')) //输出--NaN/-NaN/-0NaN -NaN:-NaN
    • 如果你使用Date 对象,那么它就简单多了。检查更新的答案
    猜你喜欢
    • 1970-01-01
    • 2022-11-28
    • 2011-12-29
    • 1970-01-01
    • 2018-01-21
    • 2021-10-09
    • 2017-01-16
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多