Making Date.parse() Work on Safari
I recently finished a project where I needed to figure out how long ago a blog post was submitted. I was using javascript and had the date that the post was submitted as a string that looked like this:
1
|
|
In order to be able to make calculation the first thing I did was changed the datePublished variable from a string into milliseconds. Date.parse returns the number of milliseconds since January 1, 1970. Initially this seemed straightforward. I used Date.parse like this:
1
|
|
Once I had the millisecond value I could find the difference between that number and the millisecond value of the current time. This was working great when I checked out the site on Chrome BUT when I went to look at the site in Safari I saw a big NaN where the time difference should be.
It turns out that Safari does not support Date.parse(). What should I do?
I searched around the web and found a cool javascript library called Moment.js. Moment.js lets you parse, manipulate and display dates. It turns strings with date information into moment object which you can then act on. I created a moment object by doing this ‘moment(publishedDate)’. Once I had the date as a moment object I could turn it into millisecond by calling a valueOf() method that is part of moment.js library.
Here’s the code:
1 2 |
|
publishedTime now has the milliseconds of the date since January 1, 1970! It’s a number that I can subtract from other numbers to find the time difference. Problem solved. Amazing.