简体   繁体   English

Moment.js .isBefore 将日期与时区偏移量进行比较

[英]Moment.js .isBefore comparing dates with a time zone offset

The two moments that need to be compared are:需要比较的两个时刻是:

  1. today now in a certain time zone (Wed Oct 12 2016 08:42:19 GMT+0000)今天现在在某个时区(2016 年 10 月 12 日星期三 08:42:19 GMT+0000)

  2. A selected date from a calendar (eg 2016-10-11)从日历中选择的日期(例如 2016-10-11)

    Here is how I am working it:这是我的工作方式:

 var date = '2016/10/12'; // october 11 var offset = '0'; // time zone offset in minutes, 0 = GMT var dateToday = moment().utcOffset(offset); // get a moment now with the time zone offset var selectedDate = moment(date, ["YYYY-MM-DD"]).utcOffset(offset); // and a moment that is the date of the day selected alert(dateToday); alert(selectedDate); if (selectedDate.isBefore(dateToday, 'day')) { alert('That date is in the past!'); } else { alert('Great!'); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://momentjs.com/downloads/moment.js"></script>

The problem appears to be that because I am in Paris time (+02:00) any offset that I select below Paris time(+02:00) for example GMT (+00:00) then that sets the select date -1 day in the past at 10:00PM.问题似乎是因为我在巴黎时间(+02:00)我选择低于巴黎时间(+02:00)的任何偏移量,例如格林威治标准时间(+00:00)然后设置选择日期-1天在过去的晚上 10:00。

So my question is how do I correctly check to see if a date (2016-10-12 GMT) is in the past?所以我的问题是如何正确检查日期(2016-10-12 GMT)是否过去?

UPDATE:更新:

I have solved it for now by extracting the date, regardless of timezone, using the format function.我现在通过使用 format 函数提取日期(无论时区如何)来解决它。 Then I created brand new moments passing the date strings explicitly into those moments like this:然后我创建了全新的时刻,将日期字符串明确地传递给这些时刻,如下所示:

 var dateToday = moment().utcOffset(offset); // get a moment now with the time zone offset var selectedDate = moment(date, ['YYYY-MM-DD']); // and a moment that is the date of the day selected var dateToday = dateToday.format('YYYY-MM-DD'); var selectedDate = selectedDate.format('YYYY-MM-DD'); var dateToday = moment(dateToday, ['YYYY-MM-DD']); var selectedDate = moment(selectedDate, ['YYYY-MM-DD']);

What about setting the selectedDate hours and minutes 00:00 or assigning an offset to it ?如何将 selectedDate 小时和分钟设置为 00:00 或为其分配偏移量?

var date = new Date();
var offset = date.getTimezoneOffset() * (-1)
selectedDate.add(offset, "hours");

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

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