1

I am trying to apply this solution to an Ember.js app. https://stackoverflow.com/a/3224854/2084924 It obviously works in the jsfiddle, but I am not able to implement it correctly in Ember.

I am learning, and probably making an obvious mistake. I've placed the function inside the model and am getting an "NaN" error. A date is passed through an input value in the format of M/D/YYYY. Anyone have experience with dates and ember? Can you see why it would fail to parse the date?

//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()
});
Community
  • 1
  • 1
manisha
  • 577
  • 2
  • 4
  • 22

2 Answers2

3

You are not reading the values from your model, you are just trying to convert the strings "startdate" and "enddate" to dates. It should be 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()
});
Karl-Johan Sjögren
  • 16,544
  • 7
  • 59
  • 68
1

try this code

//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()
});
Shayan
  • 956
  • 9
  • 20
  • this works for same reason as above. I wasn't calling the value from the object. thank you. – manisha Apr 10 '16 at 17:24
  • There would be no need to assign `var self = this;` in this scenario. It's only needed if you want to reuse inside a callback of some sort (and even then an arrow-function would produce cleaner code). – Karl-Johan Sjögren Apr 10 '16 at 18:53
  • @Karl-JohanSjögren yeah, i do it for being sure if any callback exist on function.but you right – Shayan Apr 10 '16 at 19:03