可以禁用瞬间的日光时区转换。js?
http://plnkr.co/edit/mjfelt?p=preview
$scope.obj.date = moment('2016-06-03T04:00:00.000Z');
基本上,我的应用程序仅处理事件和日期,但是MONM.JS转换日光节省时间的时间导致日期问题。它是否具有将在整个应用程序使用中禁用的设置?
如果您说的是要显示时刻显示您的日期和时间(如'z'所示,这是UTC),则应按原样使用Moment.UTC:
moment.utc('2016-06-03T04:00:00.000Z').format()
"2016-06-03T04:00:00Z"
当您使用默认矩构造函数时,就像现在一样,您正在告诉时刻将UTC时间转换为本地时间,这就是为什么您会看到时间差的原因。例如,在我的本地计算机上(我目前是UTC-5),我得到以下内容:
moment('2016-06-03T04:00:00.000Z').format()
"2016-06-02T23:00:00-05:00"
这个问题出现了很多,所以我写了这篇博客文章,该文章解释了Moment的构造函数及其如何转换ISO8601的详细日期:https://maggiepint.com/2016/05/14/moment-js-shows-wrong-wrong/
在我的情况下,由于'日光节省时间'。
我下一个时期:
{
"from": "2020-10-01 00:00:00 +0200",
"to":"2020-11-01 00:00:00 +0100",
}
和我想获得:
{
"from": "2020-10-01 00:00:00 +0200",
"to":"2020-11-01 00:00:00 +0200",
}
我的解决方案是获取当前(本地)时区并将其设置为两个日期时刻:
const currentTzOffset = moment().utcOffset(); // getting current timezone offset
const startToLocalZone = moment(from, yourDateFormat)
.local() // just checking. not sure if this is necessary
.utcOffset(currentTzOffset) // put your tz to here
.format(yourDateFormat);
const endToLocalZone = moment(to, yourDateFormat)
.local() // just checking. not sure if this is necessary
.utcOffset(currentTzOffset) // put your tz to here
.format(yourDateFormat);
console.log(startToLocalZone); // output: "2020-10-01 00:00:00 +0200"
console.log(endToLocalZone); // output: "2020-11-01 00:00:00 +0200"
和不要忘记设置您的日期格式而不是' yourdateformat '
var tz = 'America/Vancouver'; // or whatever your time zone is
var dt = '2022-03-13T07:00:00.101Z'; // or whatever date/time you're working with
var momentVal = moment.tz(dt,tz)
function isNextDayDST(mObj){
return mObj.clone().add(1, 'days').isDST();
}
function isTodayDST(mObj) {
return mObj.clone().isDST();
}
function getDSTHourCompensation(mObj) {
const todayDST = isTodayDST(mObj.clone());
const tomorrowDST = isNextDayDST(mObj.clone());
if(todayDST == false && tomorrowDST == true) {
return 1
}
if(todayDST == true && tomorrowDST == false) {
return -1
}
return 0
}
function removeDST(mObj){
const hourCompentation = getDSTHourCompensation(mObj);
return mObj.clone().add(hourCompentation, 'hours');
}
console.log(momentVal.format('YYYY-MM-DD HH:mm'))
console.log(removeDST(momentVal).format('YYYY-MM-DD HH:mm'))
也许使用时刻lib来弥补要删除特定情况的DST的时间。