使用moment.js时松开我的“diff”值

时间:2017-07-12 15:14:00

标签: javascript momentjs

我不知道发生了什么,我的算法接收 timestamp,我将它与moment.now()日期进行比较。然后使用diff在变量中指定正确的日期。

但是,由于一个不明原因,我在第一个if之后失去了差值,我尝试了一个受影响的值,并且每次都调用diff函数,但它仍然是越野车。

var timS = {"1" :1499889780000, "2" : 1500339840000, "3" :1501081920000, "4" :1501323720000, "5" : 1532912460000 ,"6" : 1499889780000, "7": 1499954196000, "8" : 1500339840000, "9" :  1501081920000, "10" :  1501323720000, "11" :  1532912460000};

for(var i = 1; i < 12; i++)
{
	console.log("Day: " +testDate(timS[i], i));
}

function testDate(timeStamp, i) {

  var day = moment(timeStamp);
  var a = moment.now();
  var diffe = day.diff(a, 'days');
  
  console.log("Have my diff value here : "+diffe+" at step :"+i);
  
  var param;

  if (diffe < 7 && diffe > 0) 
  {
  	return day.format('dddd');
  }
   if (diffe === 0) 
   {
      return day.format('[Today] dddd';
    }
  } else {
    var param2 = day.format('L');
    return param2;
  }
};

编辑:

我编辑了片段,我要做的就是返回这些值:今天和明天。为此,我正在测试now()和时间戳之间的diff。但是,正如@wildWolf指出的那样,似乎两个时间戳可以具有相同的差异,因为它们距离不到24小时... ...

我如何返回“今天”或“明天”,并且只返回这些字词(不是今天的UTC日期很长)?

1 个答案:

答案 0 :(得分:1)

您的代码存在的问题是,diff day粒度给出了天数差异,但0天差异的两个时刻可能不在同一天。例如:

moment().diff( moment().subtract(21, 'h'), 'd') // 0
moment().isSame( moment().subtract(21, 'h'), 'd') // false until 21

所以我建议使用isSame代替diff,这里有一个工作示例:

var timS = {"1" :1499889780000, "2" : 1500339840000, "3" :1501081920000, "4" :1501323720000, "5" : 1532912460000 ,"6" : 1499889780000, "7": 1499954196000, "8" : 1500339840000, "9" :  1501081920000, "10" :  1501323720000, "11" :  1532912460000};

for(var i = 1; i < 12; i++)
{
  console.log("Day: " +testDate(timS[i], i));
}

// TestDate is using into a loop, to parse all timeStamp
function testDate(timeStamp, i) {
  var day = moment(timeStamp);
  var now = moment();

  if( day.isSame(now, 'day') ){
    return day.format('[Today] dddd');
  } else if( day.isSame(now, 'week') ){
    return day.format('dddd');
  } else {
    return day.format('L');
  }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

请注意,请务必使用calendar方法执行类似于您需要的操作:

var timS = {"1" :1499889780000, "2" : 1500339840000, "3" :1501081920000, "4" :1501323720000, "5" : 1532912460000 ,"6" : 1499889780000, "7": 1499954196000, "8" : 1500339840000, "9" :  1501081920000, "10" :  1501323720000, "11" :  1532912460000};

for(var i = 1; i < 12; i++)
{
  console.log("Day: " +testDate(timS[i], i));
}

// TestDate is using into a loop, to parse all timeStamp
function testDate(timeStamp, i) {
  var day = moment(timeStamp);
  var now = moment();
  
  return day.calendar(now, {
    sameDay: '[Today] dddd',
    nextDay: 'dddd',
    nextWeek: 'dddd',
    lastDay: 'dddd',
    lastWeek: 'dddd',
    sameElse: 'L'
  });

};
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>