Search code examples
javascriptmomentjsmoment-timezone

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?


Solution

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