1

I have to convert local date and time to utc format. Therefore if I have date as 2021-08-11 (YYYY-MM-DD) and time as 2:40 PM, then slot date time should be 2021-08-11T09:10:00.000Z. I have tried multiple things, but failed

const dateTimeInUTC = moment(
  `${formattedDate} ${formatTime}`,
  'YYYY-MM-DD HH:mm:ss'
).toISOString();

above code resulted me => 2021-08-10T21:10:00.000Z (which is +5:30 more)

Also, tried following

const formatted = formattedDate + " " +formatTime (2021-08-11 02:40 PM)
const result = new Date(formatted).toISOString(); 

this gave me

Range error :Invalid Date

However, this works as expected in console, but gives error in mobile.

James Z
  • 12,209
  • 10
  • 24
  • 44
christo-pher18
  • 145
  • 1
  • 14

3 Answers3

1

I tested it now, convert - to / in date format then it will work fine in react native both on browser console and mobile. for more info you can check that link

var isoDateString = new Date('2021/08/11 12:00 pm').toISOString();
console.log(isoDateString); 

enter image description here

If you want to use your date format (date witn -) then you to add T instead of space and the time should be on 24 hour scale like

var isoDateString = new Date('2021-08-11T13:00').toISOString();

this solution will also work for you. thanks

Basir khan
  • 168
  • 8
0

you can try that

 var isoDateString = new Date('2021-08-11 2:40').toISOString();
console.log(isoDateString);
Basir khan
  • 168
  • 8
0

If you want to covert current System Time to UTC then Do :

const dateTimeInUTC = new Date().toUTCString();
console.log(dateTimeInUTC);

Or if you want convert any specific Date-Time to UTC then Do :

const dateTimeInUTC = new Date("October 13, 2000 00:45:00").toUTCString();
console.log(dateTimeInUTC);
danh
  • 62,181
  • 10
  • 95
  • 136
DSP
  • 1
  • 1