0

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?

James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

1

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

Apostolos
  • 10,033
  • 5
  • 24
  • 39
  • here below is my output: 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')) //output- -NaN/-NaN/-0NaN -NaN:-NaN – Navdeep Garg Jun 23 '21 at 07:54
  • if you use `Date` object then it is much simpler. check the updated answer – Apostolos Jun 23 '21 at 08:46