【发布时间】:2017-02-21 00:29:20
【问题描述】:
需要比较的两个时刻是:
-
今天在某个时区(2016 年 10 月 12 日星期三 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 日)是否过去?
更新:
我现在已经解决了这个问题,方法是使用 format 函数提取日期,而不考虑时区。然后我创建了全新的时刻,将日期字符串明确地传递到这样的时刻:
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']);
【问题讨论】:
-
Moment 默认解析本地时区的日期。我认为您可以从代码中删除偏移部分,一切都会正常工作。否则,您可以使用
moment.utc()比较您的 UTC 字符串。如果您需要使用多个时区,也许您可以使用moment timezone -
唯一的问题是当我选择 -XX:00 GMT 的时区时,他们的日期可能是过去的一天......例如现在它可能是 Pacific/Pago_Pago 的第 11 天,但该脚本正在验证格林威治标准时间 12 日的日期。我需要说明这一点。我试图纯粹使用 moment.js 来做到这一点,因为 time-zone.js 要求我上传时区列表,当我已经从 PHP 获得该列表(带有偏移量)时,我只是觉得这是一个人为的解决方案。不过还是谢谢!
标签: javascript jquery date momentjs