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

核能气质少年 提交于 2020-05-09 06:37:09

问题


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.


回答1:


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



回答2:


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 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 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 getMountainTime = () => {
  let 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]);
}

let denver = getMountainTime();

console.log(denver);



回答3:


You can also use date-fnc library for this.

import { formatToTimeZone } from 'date-fns-timezone';

const value = new Date();
const pattern = 'MMM. DD, YYYY [at] H:mma [MT]';

const outputDate =  formatToTimeZone(value, pattern, { timeZone: 'MST' })

This is a link to format options https://date-fns.org/v1.9.0/docs/format

And this is for date-fnc time zones https://date-fns.org/v2.0.0-alpha.27/docs/Time-Zones



来源:https://stackoverflow.com/questions/52897912/javascript-how-to-convert-utc-date-time-to-mountain-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!