0

I need a function to get UTC date-time. I passed only the date, time and time zone name only. I need to get the UTC time and date. Thank You

Ex:

const utcDate = getUTCDateTime("2022-05-10","18:00" "America/Hermosillo");

// OutPut should be like this ==>> 2022-05-11T01:00:00.527Z

function getUTCDateTime(date,time, timeZoneName){

   //Logic
   return utcDate;
}
Niranga
  • 105
  • 10
  • There are lots of similar questions (e.g. [*here*](https://stackoverflow.com/questions/72074728/how-can-i-get-the-timestamp-in-javascript-from-a-string-including-the-timezone-d)), see [*get timezone offset of another timezone in javascript without using Strings*](https://stackoverflow.com/questions/35888335/get-timezone-offset-of-another-timezone-in-javascript-without-using-strings) and [*Calculate Timezone offset only for one particular timezone*](https://stackoverflow.com/questions/61361914/calculate-timezone-offset-only-for-one-particular-timezone). – RobG May 03 '22 at 08:59

1 Answers1

0

I would use a library like Day.js for this purpose. You can parse in the date and time in a timezone, convert to UTC, then display in the desired format.

dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(customParseFormat);

function getUTCDateTime(date, time, timeZoneName) {
  const utcDate = dayjs
    .tz(`${date} ${time}`, "YYYY-MM-DD HH:mm", timeZoneName)
    .utc()
    .format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]");
  return utcDate;
}
gloo
  • 681
  • 2
  • 12