Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

346
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda