繁体   English   中英

如何在 react-native 中使用 new Date() 将 GMT 时间转换为 AM/PM?

[英]How to convert GMT time using new Date() to AM/PM in react-native?

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

这是代码:

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 以及如何克服它?

您需要包含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'))

小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM