用momentjs计算工作经验

时间:2014-12-17 08:57:12

标签: datetime momentjs

我想弄清楚如何使用momentjs来最好地计算工作经验。

假设我有以下工作:

  1. 2013年12月15日。2013年3月15日
  2. 从2013年2月20日起 - 2013年6月1日
  3. 2013年9月1日 - 2013年12月1日。
  4. 正如您所看到的,作业1和作业2之间存在重叠,作业2和作业3之间存在差距。 挑战在于我无法计算作业1开始和作业3结束之间的差异,因为作业2和作业3之间存在差距。 另一方面,我不能只为每个作业添加timediff,因为作业1和作业2之间存在重叠。

    对如何解决这个问题的任何意见表示赞赏。

    感谢,

    托马斯

1 个答案:

答案 0 :(得分:0)

遗憾的是,这个问题无法用moment.js解决。但我为您编写了一个简单的解决方案,使用整数start结束end值:

calc_duration = function(list) {

  // calculate the duration and add it to the list elements
  // when you are working with you need to adjust how x.duration
  // is retrieved
  list_with_duration = list.map( function(x){
    x.duration = x.end - x.start
    return x
  }).sort( function(a,b){
    return a.start > b.start
  });

  // sums all the durations together except for overlapping dates, there it
  // will only add the time span of the second date that exclusive of the
  // first date
  total_duration = list_with_duration.reduce( function(sum, curr, i, list){
    if (i == 0 || list[i-1].end < curr.start ) {
      return sum + curr.duration;
    } else if ( list[i-1].end > curr.end ) {
      return sum;
    } else {
      return sum + curr.end - list[i-1].end;
    }
  }, 0);

  return total_duration;

}


calc_duration([{start: 0, end: 10},{start: 5, end: 15},{start:20, end: 30}])
//returns 25

calc_duration([{start: 20, end: 30},{start: 5, end: 50},{start:0, end: 10}])
//returns 50