日期 - 每天的具体时间,具体时区 [英] Date - specific time each day, specific timezone

查看:109
本文介绍了日期 - 每天的具体时间,具体时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

**更新**



使用moment.js将会很好,如果这将使它更容易?
我想要做的是显示一个倒数计时器,每天下午至PST(6EST)下降。








我有:

 函数ShowTime(){
var now = new Date();
var hrs = 14-now.getHours();
var mins = 59-now.getMinutes();
var secs = 59-now.getSeconds();
timeLeft等等...

jsfiddle(作品),但我认为这是我自己的机器时间:
http://jsfiddle.net/36sqeq8x/



仍然不能正常工作...
我只需要倒计时至PST(6EST)每天下午3点,而不用根据他们的时区在用户端计算,就好像是否可以从GMT计算,这可能有效吗?但是这是甚至可能的。



可能是这样的组合?
https://jsfiddle.net/salman/PxzJu/

解决方案

有一个方法是创建GMT-0800时区的当前日期和15:00的日期。如果已经通过,请添加一天。如果将来有超过1天的时间(不太可能在目前为止的时区),那么减去一天。



然后从当前时间中减去毫秒到PST下午15:00。



以下使用一些帮助函数,最大的是使用 parseISO 来解析ISO 8601日期字符串,以避免内置的解析日期解析器 toISODate 用于构建15:00 PDT的字符串,其他仅用于输出。希望文档和评论是足够的。



  //在PST的15:00创建当前日期的日期(UTC-0800)//当前日期和时间值dLocal = new Date(); //创建日期相同日期但时间15:00 UTC-0800var dPST = parseISO(toISODate(dLocal)+'T'+'15: 00:00-0800'); //如果dPST已经通过,添加一个dayif(dPST< dLocal)dPST.setDate(dPST.getDate()+ 1); //如果gap太大,则减去一个dayif(dPST -  dLocal> 8.64e7)dPST.setDate(dPST.getDate() -  1); console.log('当前本地:'+ toISOString(dLocal)+'\\\
Current PST:'+ toISOStringOffset(-480,dLocal) +'\\\
下午3点PST在PST区域:'+ toISOStringOffset(-480,dPST)+'\\\
Next 3pm本地区域PST:'+ toISOString(dPST)+'\\\
ms到下午3点PST:'+ (dPST - dLocal)); / *以格式yyyy-mm-ddThh解析ISO日期字符串:mm:ss.sss + hh:mm或Z ** @param(string)s - 以ISO 8601扩展格式解析的字符串* * yyyy-mm-ddThh:mm:ss.sss +/- hh:mm或z **时区可以省略分隔符,所以+05:30或+ 0530 ** @returns {Date} - 返回一个Date对象。如果任何值超出范围,**返回无效的日期。* / function parseISO(s){//创建基础日期对象var date = new Date(); var invalidDate = new Date(NaN); //设置一些默认值var sign = -1,tzMins = 0; var tzHr,tzMin; //修剪前导和尾随空格s = s.replace(/ ^ \s * | \s * $ / g,'')。toUpperCase(); //获取部分字符串并分割成数字var d =(s.match(/ ^ \d +( - \d +){0,2} /)|| [''])[0] .split(/ \D /); var t =(s.match(/ [\sT] \d +(:\d +){0,2}(\.\d +)?/)|| [''])[0] split(/ \D /); var tz =(s.match(/ Z | [+ \-] \d\d:?\d\d $ /)|| [''])[0]; //解析时区到分钟,可以是Z,+ hh:mm或+ hhmm //分割成部分使得验证更容易,如果(tz){sign = /^-/.test(tz)? 1:-1; tzHr = tz =='Z'? 0:tz.substr(1,2); tzMin = tz =='Z'? 0:tz.substr(tz.length - 2,2)* 1; tzMins = sign *(tzHr * 60 + tzMin); } //验证函数isLeap(year){return year%4!= 0 ||年%100 == 0&&&年%400!= 0} //如果(d.length> 3 || d [1]< 1 || d [1]> 12)返回invalidDate,则检查日期部分和月份的数量是有效的// Test day is valid var monthDays = [,31,28,31,30,31,30,31,31,30,31,30,31]; var monthMax = isLeap(d [0])&& d [1] == 2? 29:monthDays [d [1]]; if(d [2]< 1 || d [1]> monthMax)return invalidDate; //测试时间部分if(t.length> 5 || t [1]> 23 || t [2]> 59 || t [3]> 59 || t [4]> 999)返回invalidDate; //在范围内测试tz if(tzHr> 12 || tzMin> 59)return invalidDate; //如果有时区,请使用UTC方法,否则本地var method = tz? '世界标准时间' : ''; //设置日期值date ['set'+ method +'FullYear'](d [0],(d [1]?d [1] -1:0),d [2] || 1); //设置时间值 - 第一个memeber是来自分隔符\s或T date ['set'+ method +'Hours'](t [1] || 0,(+ t [2] || 0)+ tzMins,t [3] || 0,t [4] || 0);返回日期;} / *返回带有局部偏移量的ISO 8601格式化字符串,例如。 2016-06-12T12:43:23.432 + 05:30 ** @param {Date} d - 从** @returns {string}转换为craete字符串,以ISO 8601格式与偏移* /函数toISOString(d){d = d || new Date(); var offset = d.getTimezoneOffset();函数z(n){return(n <10?'0':)+ n} //偏移的反向符号与ISO 8601一致var offSign = offset< 0吗'+':' - '; offset = Math.abs(offset); var offHr = z(offset / 60 | 0); var offMin = z(offset%60);返回d.getFullYear()+' - '+ z(d.getMonth()+ 1)+' - '+ z(d.getDate())+'T'+ z(d.getHours())+': '+ z(d.getMinutes())+':'+ z(d.getSeconds())+'。'+('00'+ d.getMilliseconds())。slice(-3)+ offSign + offHr + ':'+ offMin;} / *给定一个日期,返回特定时区的ISO 8601格式的日期和时间字符串** ** @param {number} offset - 以分钟为单位的偏移+ east,-west,default本地** @param {Date} d - 使用日期,默认为** @returns {string} ISO 8601格式化的字符串,用于提供的时区偏移* /函数toISOStringOffset(offset,d){//复制日期(如果提供)现在使用d = d? new Date(+ d):new Date(); //准备偏移值offset = offset || -d.getTimezoneOffset(); var offSign = offset< 0? ' - ':'+' offset = Math.abs(offset); var offHours =('0'+(offset / 60 | 0))。slice(-2); var offMins =('0'+(offset%60))。slice(-2); //将偏移应用于d d.setUTCMinutes(d.getUTCMinutes() - offset); //返回格式化的字符串返回d.getUTCFullYear()+' - '+('0'+(d.getUTCMonth()+ 1))。slice(-2)+' - '+('0'+ d.getUTCDate ())slice(-2)+'T'+('0'+ d.getUTCHours())slice(-2)+':'+('0'+ d.getUTCMinutes() -2)+':'+('0'+ d.getUTCSeconds())。slice(-2)+'。'+('000'+ d.getUTCMilliseconds())。slice(-3)+ offSign + offHours +':'+ offMins; } / *返回基于本地时间的ISO 8601格式的日期字符串**年份必须为正(即不执行-ve年)** @param {Date} date - 从** @returns创建日期字符串的日期对象{string}日期字符串yyyy-mm-dd格式或默认从** Date.prototype.toString(即无效日期)* /函数toISODate(date){return date.getDate()? ('000'+ date.getFullYear())。slice(-4)+' - '+('0'+(date.getMonth()+ 1))slice(-2)+' - '+ 0'+ date.getDate())。slice(-2):date.toString();}


** UPDATE**

using moment.js would be ok if that would make it easier? all I'm wanting to do is display a countdown timer that count down to 3pm PST (6EST) daily.


Looking for a way to have javascript get new Date() to use a specific time zome, not the user's time.

I have:

function ShowTime()  {
  var now = new Date();
  var hrs = 14-now.getHours();
  var mins = 59-now.getMinutes();
  var secs = 59-now.getSeconds();
      timeLeft etc etc...

jsfiddle (works) but I think it's my own machine's time: http://jsfiddle.net/36sqeq8x/

still not working... I just need to count down to 3pm PST (6EST) daily... without trying to calculate it on users end based on their time zone, like if could calculate from GMT, that would potentially work? but is that even possible.

maybe a combination of something like this? https://jsfiddle.net/salman/PxzJu/

解决方案

One way to go about this is to create a Date for the current date and 15:00 in time zone GMT-0800. If that's already passed, add a day to it. If it's more than 1 day in the future (unlikely in a time zone so far west) then subtract a day.

Then subtract the current time from that to get the milliseconds to the next 15:00 PST.

The following makes use of some helper functions, the largest is parseISO to parse an ISO 8601 date string to avoid parsing by the built–in Date parser. toISODate is used to build a string for 15:00 PDT, the others are just for output. Hopefully the documentation and comments is sufficient.

// Create a date for the current date at 15:00 PST (UTC-0800)
// Current date and time
var dLocal = new Date();
// Create Date for same date but time 15:00 at UTC-0800
var dPST  = parseISO(toISODate(dLocal) + 'T' + '15:00:00-0800');

// If dPST has passed, add a day
if (dPST < dLocal) dPST.setDate(dPST.getDate() + 1);
// If gap is too big, subtract a day
if (dPST - dLocal > 8.64e7) dPST.setDate(dPST.getDate() - 1);

console.log('Current local: '   + toISOString(dLocal) + 
            '\nCurrent PST:   ' + toISOStringOffset(-480, dLocal) + 
            '\nNext 3pm PST in PST zone: ' + toISOStringOffset(-480, dPST) +
            '\nNext 3pm PST in local zone: ' + toISOString(dPST) +
            '\nms to 3pm PST: ' + (dPST - dLocal)
);



/* Parse ISO date string in format yyyy-mm-ddThh:mm:ss.sss+hh:mm or Z
** @param (string} s - string to parse in ISO 8601 extended format
**                     yyyy-mm-ddThh:mm:ss.sss+/-hh:mm or z
**                     time zone can omit separator, so +05:30 or +0530
** @returns {Date}   - returns a Date object. If any value out of range,
**                     returns an invalid date.
*/
function parseISO(s) {
  // Create base Date object
  var date = new Date();
  var invalidDate = new Date(NaN);
  // Set some defaults
  var sign = -1, tzMins = 0;
  var tzHr, tzMin;
  // Trim leading and trailing whitespace
  s = s.replace(/^\s*|\s*$/g,'').toUpperCase();
  // Get parts of string and split into numbers
  var d  = (s.match(/^\d+(-\d+){0,2}/)             || [''])[0].split(/\D/);
  var t  = (s.match(/[\sT]\d+(:\d+){0,2}(\.\d+)?/) || [''])[0].split(/\D/);
  var tz = (s.match(/Z|[+\-]\d\d:?\d\d$/)          || [''])[0];

  // Resolve timezone to minutes, may be Z, +hh:mm or +hhmm
  // Splitting into parts makes validation easier
  if (tz) {
    sign  = /^-/.test(tz)? 1 : -1;
    tzHr  = tz == 'Z'? 0 : tz.substr(1,2);
    tzMin = tz == 'Z'? 0 : tz.substr(tz.length - 2, 2)*1;
    tzMins = sign * (tzHr*60 + tzMin);
  }

  // Validation
  function isLeap(year){return year % 4 != 0 || year % 100 == 0 && year % 400 != 0}
  // Check number of date parts and month is valid
  if (d.length > 3 || d[1] < 1 || d[1] > 12) return invalidDate;
  // Test day is valid
  var monthDays = [,31,28,31,30,31,30,31,31,30,31,30,31];
  var monthMax = isLeap(d[0]) && d[1] == 2? 29 : monthDays[d[1]];
  if (d[2] < 1 || d[1] > monthMax) return invalidDate;
  // Test time parts
  if (t.length > 5 || t[1] > 23 || t[2] > 59 || t[3] > 59 || t[4] > 999) return invalidDate;
  // Test tz within bounds
  if (tzHr > 12 || tzMin > 59) return invalidDate;

  // If there's a timezone, use UTC methods, otherwise local
  var method = tz? 'UTC' : '';
  
  // Set date values
  date['set' + method + 'FullYear'](d[0], (d[1]? d[1]-1 : 0), d[2]||1);
  // Set time values - first memeber is '' from separator \s or T
  date['set' + method + 'Hours'](t[1] || 0, (+t[2]||0) + tzMins, t[3]||0, t[4]||0);

  return date;
}

/* Return ISO 8601 formatted string with local offset, e.g. 2016-06-12T12:43:23.432+05:30
** @param {Date} d - date to craete string from
** @returns {string} in ISO 8601 format with offset
*/
function toISOString(d) {
  d = d || new Date();
  var offset = d.getTimezoneOffset();
  function z(n){return (n<10?'0':'') + n}
  // Reverse signe of offset to be consistent with ISO 8601
  var offSign = offset < 0? '+' : '-';
  offset = Math.abs(offset);
  var offHr  = z(offset/60 | 0);
  var offMin = z(offset%60);
  return d.getFullYear() + '-' + z(d.getMonth() + 1) + '-' + z(d.getDate()) + 'T' +
         z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds()) + '.' +
         ('00' + d.getMilliseconds()).slice(-3) + offSign + offHr + ':' + offMin;
}

/* Given a Date, return an ISO 8601 formatted date and time string
** for a particular time zone.
** @param {number} offset - offset in minutes +east, -west, default is local
** @param {Date} d - date to use, default is now
** @returns {string} ISO 8601 formatted string for supplied time zone offset
*/
function toISOStringOffset(offset, d) {
  // Copy date if supplied or use now
  d = d? new Date(+d) : new Date();
  // Prepare offset values
  offset = offset || -d.getTimezoneOffset();
  var offSign = offset < 0? '-' : '+'; 
  offset = Math.abs(offset);
  var offHours = ('0' + (offset/60 | 0)).slice(-2);
  var offMins  = ('0' + (offset % 60)).slice(-2);

  // Apply offset to d
  d.setUTCMinutes(d.getUTCMinutes() - offset);

  // Return formatted string
  return d.getUTCFullYear() + 
    '-' + ('0' + (d.getUTCMonth()+1)).slice(-2) + 
    '-' + ('0' + d.getUTCDate()).slice(-2) + 
    'T' + ('0' + d.getUTCHours()).slice(-2) + 
    ':' + ('0' + d.getUTCMinutes()).slice(-2) + 
    ':' + ('0' + d.getUTCSeconds()).slice(-2) + 
    '.' + ('000' + d.getUTCMilliseconds()).slice(-3) +
    offSign + offHours + ':' + offMins; 
}

/* Return an ISO 8601 formatted date string based on local time
** Year must be positive (i.e. doesn't do -ve year)
** @param {Date} date - date object to create date string from
** @returns {string} dates string in yyyy-mm-dd format or default from
**                   Date.prototype.toString (i.e. "Invalid Date")
*/
function toISODate(date) {
  return date.getDate()? ('000' + date.getFullYear()).slice(-4) + '-' +
                         ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
                         ('0' + date.getDate()).slice(-2) : date.toString();
}

这篇关于日期 - 每天的具体时间,具体时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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