Home > Software design >  Convert HH:mm to UTC date time in JavaScript using date-fns
Convert HH:mm to UTC date time in JavaScript using date-fns

Time:05-06

I'm working on an appointment booking React app where a teacher can set their virtual office hours in the form of a time slot.

let availability = ["09:00", "17:00"]; // from 9 AM to 5 PM local time

Since this time is local to the teacher, I'd like to store it as UTC time in the ISO 8601 format so that if a student is in a different region, I can parse it on the client and show this time in their appropriate timezone.

I tried using the parse function from [email protected] like this

parse('09:00', 'HH:mm', new Date()); // => Wed Jan 01 0020 00:00:00 GMT-0456 (Eastern Daylight Time)

But, this didn't return the time in my timezone (Central Standard Time).

Is there a way to represent this local time slot in UTC?

CodePudding user response:

Not sure if this is your desired output

const inputTime = "09:00";

const outputDate = new Date(new Date().toJSON().slice(0, 10)   " "   inputTime).toUTCString();

console.log(outputDate);

CodePudding user response:

I came to a solution which was inspired by @Anas Abdullah Al. Here are two simple functions which will convert from both UTC and a user's local time.

const format = window.dateFns.format;

const convertLocalToUTC = (localTime) => {
  if (!localTime) {
    throw new Error("Time can't be empty");
  }
  return new Date(`${new Date().toJSON().slice(0, 10)} ${localTime}`)
    .toISOString()
    .slice(11, 16);
};

const convertUTCToLocal = (UTCTime) => {
  if (!UTCTime) {
    throw new Error("Time can't be empty");
  }
  const currentUTCDate = new Date().toISOString().substring(0, 10);
  const inputUTCDateTime = `${currentUTCDate}T${UTCTime}:00.000Z`;
  return format(new Date(inputUTCDateTime), "HH:mm");
};

const UTCTime = "14:00";
const localTime = "09:00";

console.log(convertLocalToUTC(localTime)); // 14:00 UTC
console.log(convertUTCToLocal(UTCTime)); // 09:00 CST
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/2.0.0-alpha0/date_fns.min.js"></script>

Hope this helps someone else.

  • Related