user5303752
user5303752

Reputation:

Date object in safari

I am using safari 8.0, And I try to do

 new Date('sat-oct-10-2015');

on chrome the result is Date object with the right date. But on safari the result is

 Invalid Date

how can I work with dates in this format in safari?

Upvotes: 0

Views: 264

Answers (4)

RobG
RobG

Reputation: 147513

Do not use the Date constructor (or Date.parse) to parse strings. Until ES5, parsing of date strings was entirely implementation dependent. After that, the long form of ISO 8606 has been specified, however parts of that changed with ECMAScript 2015 so that even using specified formats is not consistent across browsers (e.g. 2015-10-15 12:00:00 may result in 3 different results in browsers currently in use).

The solution is to manually parse date strings, either write your own function (which is not difficult if you only need to support one format) or use a small library.

Upvotes: 1

baao
baao

Reputation: 73281

I'd suggest using moment.js for dates in JavaScript. Then you can simply parse the date with

moment('sat-oct-10-2015', 'ddd-MMM-DD-YYYY').format();

moments API has good support in all major browsers and eases date manipulating and displaying with JavaScript.

Upvotes: 0

lxg
lxg

Reputation: 13127

When creating a Date object with a “human-readable” string, you must use a certain format, usually conforming to RFC2822 or ISO 8601.

It may be that a browser is able to process your new Date('sat-oct-10-2015');, but this is not demanded by the specifications.

Hint: Look at some other ways to create a date object, for example with a Unix timestamp. This is easier and more reliable than the dateString approach.

Upvotes: 1

rajuGT
rajuGT

Reputation: 6414

Always try to use the standard date format specified by ECMAScript ISO format.

Date.parse() i.e Date constructor will always produce the expected result if you use the standard string format. Also the browser may support additional string formats, but that may not be supported by all other browser vendors.

Upvotes: 1

Related Questions