如何在不创建新时刻对象的情况下获得所需时区的小时和分钟?

时间:2015-12-16 23:37:31

标签: javascript timezone momentjs

我必须以这种格式在网页上显示一个字符串:16:00 HH:mm

我使用时刻对象来表示日期/时间和时区。

var day = moment().tz('GMT');
day.hours(16).minutes(0).seconds(0).milliseconds(0);

所以这是格林尼治标准时间的16:00。

在我的网页上,我想更改时区,然后收集小时和分钟。

如果我制作一个新的时刻对象

var day2 = moment().tz('PST); //this is 8 AM since gmt was 16
console.log(day2.get('hours'));

是16而不是8!

并尝试获取GMT中的小时和分钟,而不是PST。

我如何在PST中获取它?我必须继续包装吗?

3 个答案:

答案 0 :(得分:4)

// initialize a new moment object to midnight UTC of the current UTC day
var m1 = moment.utc().startOf('day'); 

// set the time you desire, in UTC
m1.hours(16).minutes(0);

// clone the existing moment object to create a new one
var m2 = moment(m1);   // OR  var m2 = m1.clone();   (both do the same thing)

// set the time zone of the new object
m2.tz('America/Los_Angeles');

// format the output for display
console.log(m2.format('HH:mm'));

Working jsFiddle here.

如果无法使其正常工作,则表示您没有正确加载时刻,时刻时区和所需的时区数据。对于数据,您需要使用您关注的区域的区域数据来调用moment.tz.add,或者您需要使用网站上提供的一个与时间同步的数据文件。

在小提琴中,您可以通过展开“外部资源”部分来查看我正在加载的时刻文件。

fiddle resources

答案 1 :(得分:1)

PST在不同地区可能意味着不同的东西。在时刻 - 时区文档中,我看不到任何涉及" PST"或类似的缩写。

也许试试:

var day2 = moment().tz('PST'); 
// 16 with Error: Moment Timezone has no data for PST. See http://momentjs.com/timezone/docs/#/data-loading/.

var day2 = moment().tz('America/Los_Angeles'); 
// 15

答案 2 :(得分:0)

我不知道使用moment.js,但使用POJS相当简单,同样的算法也应该有效。只需从日期对象的UTC时间减去8小时,然后根据调整后的UTC时间返回格式化字符串。

假设PST是“太平洋标准时间”,也称为“太平洋时间”(PT),并且是UTC -8:00:

/* @param {Date} date - input date object
** @returns {string} - time as hh:mm:ss
**
** Subtract 8 hours from date UTC time and return a formatted times string
*/
function getPSTTime(date) {
  var d = new Date(+date);
  d.setUTCHours(d.getUTCHours() - 8);
  return ('0' + d.getUTCHours()).slice(-2) + ':' +
         ('0' + d.getUTCMinutes()).slice(-2) + ':' +
         ('0' + d.getUTCSeconds()).slice(-2);
}

document.write('Current PST time: ' + getPSTTime(new Date));

moment-timezoneIANA time zones的moment.js添加功能。对于PST,您可以使用America / Los_Angeles,但它也可能会自动调整夏令时,因此您可以在适用时获得PDT。如果您想忽略夏令时,请使用上面的内容或找到您需要的偏移量的位置并使用它。