Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 463
user1200940 Avatar asked Sep 14 '25 22:09

user1200940


2 Answers

Depending on your browser support needs, you may be able to use toLocaleString but be aware that locales and options may not be supported in Edge and are not supported in Android webview.

new Date().toLocaleString('en-US', {timeZone: 'America/Denver'})

To follow your function through to conclusion and convert UTC time to Mountain Time manually (either Mountain Standard Time or Mountain Daylight Time depending on the time of year), you would have to extend your function to handle daylight savings. For example (this is why libraries like Moment.js are so popular, and may be worth looking into for your needs):

const twoDigit = (d) => (d < 10 ? '0' : '') + d;
const formatDate = (date, time) => {
  date = date.map((x) => twoDigit(x)).join('/');
  time = time.map((x) => twoDigit(x)).join(':');
  return `${date} ${time}`;
};

const getOffset = (month, date, day, hour) => {
  // assume MST offset
  let offset = 7;
  
  // adjust to MDT offset as needed
  if ((month > 2 && month < 10) || (month === 2 && date > 14)) {
    offset = 6;
  } else if (month === 2 && date > 7 && date < 15) {
    if ((day && date - day > 7) || (day === 0 && hour - offset >= 2)) {
      offset = 6;
    }
  } else if (month === 10 && date < 8) {
    if ((day && date - day < 0) || (day === 0 && hour - offset < 1)) {
      offset = 6;
    }
  }
  
  return offset;
};

const getMountainTime = () => {
  const dt = new Date(); // current datetime
  let year = dt.getUTCFullYear(); // utc year
  let month = dt.getUTCMonth(); // utc month (jan is 0)
  let date = dt.getUTCDate(); // utc date
  let hour = dt.getUTCHours(); // utc hours (midnight is 0)
  let minute = dt.getUTCMinutes(); // utc minutes
  let second = dt.getUTCSeconds(); // utc seconds
  let day = dt.getUTCDay(); // utc weekday (sunday is 0)
  let offset = getOffset(month, date, day, hour);
  if (hour - offset < 0) {
    hour = 24 + hour - offset;
    day = day ? day - 1 : 6;
    if (date === 1) {
      if (!month) {
        year -= 1;
        month = 11;
      } else {
        month -= 1;
      }
      
      date = new Date(year, month + 1, 0).getDate();
    } else {
      date -= 1;
    } 
  } else {
    hour -= offset;
  }
  
  month += 1;
  return formatDate([month, date, year], [hour, minute, second]);
};

const denver = getMountainTime();
console.log(denver);
like image 98
benvc Avatar answered Sep 16 '25 13:09

benvc


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">
like image 40
Towkir Avatar answered Sep 16 '25 11:09

Towkir