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

182
Views
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 answers
Answer question

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