Search code examples
javascriptdatetimetimezoneutc

JavaScript: How to convert UTC date / time to Mountain Time?


I have been trying to write a script that will take the current time in Denver and output it into a URL.

I have been able to get this far: http://jsfiddle.net/Chibears85/h41wu8vz/4/

JS

$(function() {
  var today = new Date();
  var ss = today.getUTCSeconds();
  var nn = today.getUTCMinutes() - 3; //3 minute delay
  var hh = today.getUTCHours() - 6; //Offset UTC by 6 hours (Mountain Time)
  var dd = today.getUTCDate();
  var mm = today.getUTCMonth() + 1; //January is 0!
  var yyyy = today.getUTCFullYear();
  if (dd < 10) {
    dd = '0' + dd
  }
  if (mm < 10) {
    mm = '0' + mm
  }
  if (hh < 10) {
    hh = '0' + hh
  }

  var today = mm + '/' + dd + '/' + yyyy + '%20' + hh + ':' + nn + ':' + ss ;
  $('img.r').each(function() {
    var url = $(this).attr('src');
    if (url.indexOf("?") >= 0) {
      $(this).attr("src", url + today);
    } else {
      $(this).attr("src", url + "?feature_date=" + today);
    }
  });
});

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="screen.js"></script>
<img class="r" src="https://mywebsite.com&DateTime=" width="400">

It inserts the date into the URL however from 6pm-12am Mountain Time the time breaks (01:00:00 10/20/2018 becomes -5:00:00 10/20/2018 instead of 19:00:00 10/19/2018) and the 3 minute delay offset makes it break every hour from :00-:02 (1:01 becomes 1:-02 instead of 00:59).

I was wondering how I can fix the UTC offset so it doesn't subtract into negatives and offsets the date/month/year as appropriate.


Solution

  • This can be solved with pure JS, though I thought of using MomentJS at first. A good solution would be this:

    var today = new Date();
    var todayThreeMinutesLess = new Date(today - (3  * 60000)); // to reduce 3 minutes from current time, as 60000 ms is 1 minute;
    var today = todayThreeMinutesLess.toLocaleString('en-US', {timeZone: 'America/Denver', hour12: false}).replace(', ', '%20');
    $('img.r').each(function() {
        var url = $(this).attr('src');
        if (url.indexOf("?") >= 0) {
          $(this).attr("src", url + today);
        } else {
          $(this).attr("src", url + "?feature_date=" + today);
          // just to prevew the url format
          $(this).attr("alt", url + "?feature_date=" + today);
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img class="r" src="https://mywebsite.com&DateTime=" width="400">