由周和工作日定义的两个时刻的Moment.js差异给出了错误的结果

时间:2014-08-18 08:10:43

标签: javascript momentjs

我想计算由工作日,小时和分钟定义的片刻(itemMoment)和now(nowMoment)之间的差异。如果itemMoment在nowMoment(diff< 0)之前,我想添加一周并再次计算差异,但是添加一周(周:我的代码中的周+ 1)不会改变差异,我仍然有负面的差异。

这是我第一次使用moment.js库,所以我可能不知道如何正确使用它。如果有经验的人可以提供帮助,那就太好了。

var now = moment();
  var year = now.year();
  var week = now.week();
  var weekday = now.weekday();
  var hour = now.hour();
  var minute = now.minute();

var itemMoment = moment({
                                day: item.weekday,
                                hour: item.hour,
                                minute: item.minute
                            });
    var nowMoment = moment({
                                day: weekday,
                                hour: hour,
                                minute: minute
                            });

    if (itemMoment.diff(nowMoment) > 0) {
        item.date = moment({
                            year: year, 
                            week: week, 
                            weekday: item.weekday, 
                            hour: item.hour, 
                            minute: item.minute
                        });
        diff = itemMoment.diff(nowMoment);
    }
    else {
        if (week == 51) {
            week = -1;
            year = year + 1
        }
        item.date = moment({
                            year: year, 
                            week: week + 1, 
                            weekday: item.weekday, 
                            hour: item.hour, 
                            minute: item.minute
                        });
        diff = item.date.diff(now);

1 个答案:

答案 0 :(得分:1)

你可以使用isBefore()或isAfter()进行比较。 http://momentjs.com/docs/#/query/

if (itemMoment.isBefore(nowMoment)) {

然后你可以像这样进行操作:http://momentjs.com/docs/#/manipulating/

item.date = itemMoment.add('weeks', 1);