2

I have a date-filter component that I am using in my Ember application that only works on initial render, not on a page reload, or even if I save a file (which triggers the application to live update).

In the main template of my application, I render the date-filter like this passing it a unix timestamp

{{date-filter unixepoch=item.date}}

Then, in components/date-filter.js, I use a computed property called timeConverter to change the unix epoch into a time string formatted according to user's language of choice, and then in my templates/components/date-filter.hbs file I do {{timeConverter}} to display the results

timeConverter: function(){
    //step 1: get the epoch I passed in to the component
    var epoch = this.get('unixepoch');
    //step 2: create a human readable date string such as `Jun 29, 2015, 12:36PM`
    var datestring = new Date(epoch)

    //do language formatting --code omitted as the problem is with step2

}

It is step 2 that fails (returning invalid date) if I refresh the page or even save the file. It always returns the proper date string the first time this component is called. Even if I do new Date(epoch) in the parent component, and try to pass the result in to this component (to do foreign language formatting), I'm having the same problem.

Question: how can I figure out what's happening inside new Date(epoch), or whether it's an issue related to the component?

BrainLikeADullPencil
  • 11,313
  • 24
  • 78
  • 134

1 Answers1

10

I suspect your epoch value is a string (of all digits). If so, then

var datestring = new Date(+epoch);
// Note ------------------^

...will fix it by converting it to a number (+ is just one way to do it, this answer lists your options and their pros/cons). Note that JavaScript uses the newer "milliseconds since The Epoch" rather than the older (original) "seconds since The Epoch." So if doing this starts giving you dates, but they're much further back in time than you were expecting, you might want epoch * 1000 to convert seconds to milliseconds.

If it's a string that isn't all digits, it's not an epoch value at all. The only string value that the specification requires new Date to understand is the one described in the spec here (although all major JavaScript engines also understand the undocumented format using / [not -] in U.S. date order [regardless of locale]: mm/dd/yyyy — don't use it, use the standard one).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Took some time to figure out that '+', thank you, you saved some time for me :) – Bakavani Feb 23 '22 at 13:59
  • @Bakavani - :-) Some further options and explanation here: https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875 – T.J. Crowder Feb 23 '22 at 14:41