简体   繁体   English

moment.js返回不同的时区

[英]moment.js returns different timezones

I'm using this code to create 2 dates that represent a filter date range (in this case the last 3 months): 我正在使用此代码创建2个代表过滤日期范围的日期(在本例中为过去3个月):

$ctrl.startDate = moment().utc().startOf('month').add(-2, 'months').toDate();
$ctrl.endDate = moment().utc().endOf('month').add(0, 'months').toDate();

However the first returned date is timezone CET (GMT+1) (which is my zone) and the second is CEST (GMT+2). 但是,第一个返回的日期是时区CET(GMT + 1)(这是我的区域),第二个是CEST(GMT + 2)。 I have no idea why! 我不知道为什么! I have tried using utc() to get "neutral" dates without success. 我已经尝试使用utc()获得“中立”日期但没有成功。

Returned dates: 退回日期:

01.01.2017 01:00:00 CET 01.01.2017 01:00:00 CET

01.04.2017 01:59:59 CEST 01.04.2017 01:59:59 CEST

I want either GMT or CET but the same zone! 我想要GMT或CET,但需要相同的区域! Where does moment take these 2 zones from? 这些2个区域的时刻在哪里?

I've come so far that I think it is a bug. 我到目前为止,我认为这是一个错误。

I use version 2.17.1 我使用的是2.17.1版本

Any ideas? 有任何想法吗?

JSFIDDLE: https://jsfiddle.net/FLhpq/8807/ JSFIDDLE: https ://jsfiddle.net/FLhpq/8807/

I don't know if you can consider it a bug, in your fiddle you are showing in the result of toDate() that as docs says: 我不知道你是否可以把它视为一个bug,你在toDate()的结果中表现出来,正如文档所说:

get the native Date object that Moment.js wraps 获取Moment.js包装的本机Date对象

If you look at momentjs the code you will see that toDate() implementation: 如果你看看momentjs代码,你会看到toDate()实现:

function toDate () {
    return new Date(this.valueOf());
}

simply uses new Date() that returns a JavaScript date object in local time, see MDN Date : 只需使用new Date()本地时间返回JavaScript日期对象,请参阅MDN日期

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. 注意:如果将Date作为具有多个参数的构造函数调用,则指定的参数表示本地时间。 If UTC is desired, use new Date( Date.UTC(...) ) with the same arguments. 如果需要UTC,请使用具有相同参数的新日期( Date.UTC(...) )。

If you use format() in your code you will always see +00:00 offset. 如果在代码中使用format() ,则总会看到+00:00偏移量。

 var divUtc = $('#divUTC'); var divLocal = $('#divLocal'); var startDate = moment.utc().startOf('month').add(-2, 'months').format('YYYY-MM-DDTHH:mm:ssZ'); var endDate = moment.utc().endOf('month').add(0, 'months').format('YYYY-MM-DDTHH:mm:ssZ'); //put UTC time into divUTC divUtc.text(startDate); divLocal.text(endDate); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script> UTC<br/> <div id="divUTC"></div><br/> Your Local Time with respect to above UTC time<br/> <div id="divLocal"> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM