'Get UTC date time by Date and time Zone name

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;
}


Solution 1:[1]

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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1