节点时刻-特定时区的endOf('day')

时间:2019-04-17 11:25:36

标签: node.js momentjs

我想为今天的23:59:59创建一个矩对象,对于特定的时区,例如亚洲/耶路撒冷

运行moment().endOf('day').utc('Asia/Jerusalem')

返回moment.utc("2019-04-17T23:59:59.999+00:00")

哪个不好,因为23:59 UTC + 0!= 23:59 UTC + 2(耶路撒冷时区)

设置默认时区(即process.env.TZ = 'Asia/Jerusalem')可以解决此问题,但是我不想每次都需要更改环境env。

如何创建具有固定时区的时刻对象?

2 个答案:

答案 0 :(得分:1)

为此,您应该使用moment-timezone

const moment = require('moment-timezone');

const dt = moment().tz('Asia/Jerusalem').endOf('day');

dt.toISOString(); // 2019-04-17T20:59:59.999Z
dt.format(); // 2019-04-17T23:59:59+03:00

是的,Asia/Jerusalem现在是+03:00

答案 1 :(得分:0)

我认为您可以使用此函数在任何时区中结束一天的工作,而无需使用任何较大的lib或过时的时区偏移量,因为那有时会需要更新moment.js

var date = new Date()
var options = {
  // hour: 'numeric', minute: 'numeric', second: 'numeric',
  year: 'numeric', month: 'numeric', day: 'numeric',
  // hour12: false,
  timeZoneName: 'short',
  timeZone: 'Asia/Jerusalem'
};
var date = new Intl.DateTimeFormat('xx-XX', options)
  .format(date).split(' ') // [date, offset]

date = `${date[0]} 23:59:59:999 ${date[1]}` // use end of day
  

// end of day in Asia/Jerusalem
console.log(date)
date = new Date(date)

// end of day in Asia/Jerusalem with no timezone
console.log(date)


// end of day in Asia/Jerusalem with our local timezone
console.log(date.toLocaleDateString(), date.toLocaleTimeString())