简体   繁体   中英

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. I am getting issue while converting time (in GMT 5:30 IST) to AM/PM. It adds 5:30 hours in local current time. eg. From database time 3:00PM. 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. when i am converting this GMT time to Am/PM again when i need. It shows 8:30PM instead of 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?

You need moment-timezone to be included and then you can do the following by using utcOffset method

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:

 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

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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