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

183
Visualizações
JavaScript get UTC from local midnight

I have a date that comes from a Bootstrap DateTimePicker $('#datetimepicker').find("input").val() that has the format "mm/dd/yyyy".

<div class='input-group date' id='datetimepicker'>
  <form autocomplete="off" onkeydown="return event.key != 'Enter';">
      <input type='text' autofill="off" readonly class="form-control" />
  </form>
  <span class="input-group-addon">
     <span class="glyphicon glyphicon-calendar"></span>
  </span>
</div>

I'm trying to get the UTC date and time for the selected date, at midnight, using Moment js:

moment.utc($('#datetimepicker').find("input").val()).tz(timezone).format('YYYY-MM-DD HH:mm:ss')

For example, starting date from the picker is 01/21/2022 and the timezone is America/Phoenix which is UTC-7.

I should have 2022-01-21 07:00:00 but my code returns 2022-01-20 17:00:00.

What am I doing wrong? Is there a way to get the UTC time for a day at 00:00 time, just by knowing the timezone?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have to create the timestamp in your local timezone first, and then convert it to UTC. You are doing it the other way around. Ie if I split up your code snippet, you are doing the following

let thedate = $('#datetimepicker').find("input").val();
let utcdate = moment.utc(thedate);
let localdate = utcdate.tz(timezone);

Thus, the timezone offset is, of course, added in the wrong direction ...

Try the following

function getTime() {
  let thedate = $('#thedate').val();
  console.log(thedate)
  
  // create a timestamp in the respective timezone
  let localdate = moment.tz(thedate, "America/Phoenix");
  // convert it to utc
  let utcdate = localdate.utc();
  // format the timestamp
  console.log(utcdate.format("YYYY-MM-DD HH:mm:ss"));
}
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="thedate" type="date">
<input type="button" onClick="getTime()" value="Get Time">

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