简体   繁体   English

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

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

I am working in a react-native project and using moment library.我正在一个 react-native 项目中工作并使用 moment 库。 I am getting issue while converting time (in GMT 5:30 IST) to AM/PM.我在将时间(格林威治标准时间 5:30 IST)转换为 AM/PM 时遇到问题。 It adds 5:30 hours in local current time.它增加了当地当前时间 5:30 小时。 eg.例如。 From database time 3:00PM.从数据库时间下午 3:00 开始。 After passing from new Date() => time converts to Wed Jun 23 2021 15:00:00 GMT+0530 (India Standard Time) and in the field where i need.从 new Date() => 传递后,时间将转换为Wed Jun 23 2021 15:00:00 GMT+0530 (印度标准时间)以及我需要的字段。 when i am converting this GMT time to Am/PM again when i need.当我需要时再次将此格林威治标准时间转换为上午/下午时。 It shows 8:30PM instead of 3:00PM.它显示 8:30PM 而不是 3:00PM。

Here is the code:这是代码:

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

Why GMT time is adding 5:30 in current time and how to overcome from it?为什么 GMT 时间在当前时间增加 5:30 以及如何克服它?

You need moment-timezone to be included and then you can do the following by using utcOffset method您需要包含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'))

If you are working with Date object, you can do the following:如果您正在使用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'))

If you have the stated strings and you need to preserve the time regardless of the timezone, then just use substring and then apply moment如果您有指定的字符串,并且无论时区如何都需要保留时间,那么只需使用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小提琴

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

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