Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

348
Views
Convert HH:mm to UTC date time in JavaScript using date-fns

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 date-fns@2.22.1 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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!