需要比较的两个时刻是:
今天在某个时区 (Wed Oct 12 2016 08:42:19 GMT+0000)
从日历中选择一个日期(例如 2016-10-11)
这是我的工作方式:
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>
问题似乎是因为我在巴黎时间 (+02:00) 我选择的任何偏移量低于巴黎时间 (+02:00) 例如 GMT (+00:00) 然后设置选择日期-1 天前的晚上 10:00。
所以我的问题是如何正确检查日期 (2016-10-12 GMT) 是否已过去?
更新:
我现在已经通过使用格式函数提取日期(无论时区如何)解决了这个问题。然后我创建了全新的时刻,将日期字符串显式传递到这些时刻,如下所示:
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']);
最佳答案
如何设置 selectedDate 小时和分钟 00:00 或为其分配一个偏移量?
var date = new Date();
var offset = date.getTimezoneOffset() * (-1)
selectedDate.add(offset, "hours");
关于javascript - Moment.js .isBefore 将日期与时区偏移量进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39994618/