JavaScript:如何将UTC日期/时间转换为山区时间? [英] JavaScript: How to convert UTC date / time to Mountain Time?

查看:66
本文介绍了JavaScript:如何将UTC日期/时间转换为山区时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试编写一个脚本,该脚本将花费丹佛当前时间并将其输出到URL。

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

我能够做到这一点: 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">

它将日期插入URL,但是从山区时间6 pm-12am开始,时间会中断(01:00 :00 10/20/2018变为-5:00:00 10/20/2018而不是19:00:00 10/19/2018),并且3分钟的延迟偏移使其每小时从:00-:02( 1:01变为1:-02,而不是00:59)。

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).

我想知道如何解决UTC偏移量,以便它不减去负数,并适当地偏移日期/月份/年份。

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.

推荐答案

这可以用纯JS解决,尽管我最初考虑使用MomentJS。
一个好的解决方案是:

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

这篇关于JavaScript:如何将UTC日期/时间转换为山区时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆