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

标签 javascript jquery date momentjs

需要比较的两个时刻是:

  1. 今天在某个时区 (Wed Oct 12 2016 08:42:19 GMT+0000)

  2. 从日历中选择一个日期(例如 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/

相关文章:

javascript - 如何使用 pubnub chatengine 添加私有(private)一对一聊天?

javascript - 尝试通过 AJAX 发送输入文件数据,无法访问我的 Controller 中的数据

jquery - 在 jQuery 上使用 !important 更改 fullcalendar 的 css 类属性

java - 在java中格式化包含日期的字符串时出现问题

javascript - 如何在 google maps JavaScript API v3 上隐藏或禁用 google Logo 、页脚、版权?

javascript - 如何在主干模型属性中设置 bool 值 true/false

javascript - 如何激活另一个 html 文件中的链接?

javascript - 消除点击按钮时的短暂延迟或滞后

java - 日期时间转换为特定格式

java - 我如何计算给定日期列表中周数的日期数