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

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

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