计算Ember.js中的日期差异

时间:2016-04-10 17:00:10

标签: javascript ember.js

我正在尝试将此解决方案应用于Ember.js应用。 https://stackoverflow.com/a/3224854/2084924 它显然适用于jsfiddle,但我无法在Ember中正确实现它。

我正在学习,可能犯了一个明显的错误。我已将该函数放在模型中,并且出现“NaN”错误。日期以M / D / YYYY格式传递输入值。谁有日期和余烬的经验?你能明白为什么它不能解析日期吗?

//app/model/task.js
import DS from 'ember-data';

export default DS.Model.extend({
  taskname: DS.attr(),
  startdate: DS.attr(),
  enddate: DS.attr(),
  duration: Ember.computed('startdate', 'enddate', function() {
    var date1 = new Date('startdate');
    var date2 = new Date('enddate');
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
    return diffDays;
  }),
  banding: DS.attr()
});

2 个答案:

答案 0 :(得分:3)

您没有从模型中读取值,您只是尝试将字符串“startdate”和“enddate”转换为日期。它应该是new Date(this.get('startdate'));

import DS from 'ember-data';

export default DS.Model.extend({
  taskname: DS.attr(),
  startdate: DS.attr(),
  enddate: DS.attr(),
  duration: Ember.computed('startdate', 'enddate', function() {
    var date1 = new Date(this.get('startdate'));
    var date2 = new Date(this.get('enddate'));
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
    return diffDays;
  }),
  banding: DS.attr()
});

答案 1 :(得分:1)

试试这段代码

//app/model/task.js
import DS from 'ember-data';

export default DS.Model.extend({
  taskname: DS.attr(),
  startdate: DS.attr(),
  enddate: DS.attr(),
  duration: Ember.computed('startdate', 'enddate', function() {
    var self = this;
    var date1 = new Date(self.get('startdate'));
    var date2 = new Date(self.get('enddate'));
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
    return diffDays;
  }),
  banding: DS.attr()
});