Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

354
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda