[javascript] Invalid date in safari

 alert(new Date('2010-11-29'));

chrome, ff doesn't have problems with this, but safari cries "invalid date". Why ?

edit : ok, as per the comments below, I used string parsing and tried this :

alert(new Date('11-29-2010')); //doesn't work in safari
alert(new Date('29-11-2010')); //doesn't work in safari
alert(new Date('2010-29-11')); //doesn't work in safari

edit Mar 22 2018 : Seems like people are still landing here - Today, I would use moment or date-fns and be done with it. Date-fns is very much pain free and light as well.

This question is related to javascript date safari

The answer is


Use the below format, it would work on all the browsers

var year = 2016;
var month = 02;           // month varies from 0-11 (Jan-Dec)
var day = 23;

month = month<10?"0"+month:month;        // to ensure YYYY-MM-DD format
day = day<10?"0"+day:day;

dateObj = new Date(year+"-"+month+"-"+day);

alert(dateObj); 

//Your output would look like this "Wed Mar 23 2016 00:00:00 GMT+0530 (IST)"

//Note this would be in the current timezone in this case denoted by IST, to convert to UTC timezone you can include

alert(dateObj.toUTCSting);

//Your output now would like this "Tue, 22 Mar 2016 18:30:00 GMT"

Note that now the dateObj shows the time in GMT format, also note that the date and time have been changed correspondingly.

The "toUTCSting" function retrieves the corresponding time at the Greenwich meridian. This it accomplishes by establishing the time difference between your current timezone to the Greenwich Meridian timezone.

In the above case the time before conversion was 00:00 hours and minutes on the 23rd of March in the year 2016. And after conversion from GMT+0530 (IST) hours to GMT (it basically subtracts 5.30 hours from the given timestamp in this case) the time reflects 18.30 hours on the 22nd of March in the year 2016 (exactly 5.30 hours behind the first time).

Further to convert any date object to timestamp you can use

alert(dateObj.getTime());

//output would look something similar to this "1458671400000"

This would give you the unique timestamp of the time


Best way to do it is by using the following format:

new Date(year, month, day, hours, minutes, seconds, milliseconds)
var d = new Date(2018, 11, 24, 10, 33, 30, 0);

This is supported in all browsers and will not give you any issues. Please note that the months are written from 0 to 11.


This is not the best solution, although I simply catch the error and send back current date. I personally feel like not solving Safari issues, if users want to use a sh*t non-standards compliant browser - they have to live with quirks.

function safeDate(dateString = "") {
  let date = new Date();
  try {
    if (Date.parse(dateString)) {
      date = new Date(Date.parse(dateString))
    }
  } catch (error) {
    // do nothing.
  }
  return date;
}

I'd suggest having your backend send ISO dates.


This will not work alert(new Date('2010-11-29')); safari have some weird/strict way of processing date format alert(new Date(String('2010-11-29'))); try like this.

(Or)

Using Moment js will solve the issue though, After ios 14 the safari gets even weird

Try this alert(moment(String("2015-12-31 00:00:00")));

Moment JS


I was facing a similar issue. Date.Parse("DATESTRING") was working on Chrome (Version 59.0.3071.115 ) but not of Safari (Version 10.1.1 (11603.2.5) )

Safari:

Date.parse("2017-01-22 11:57:00")
NaN

Chrome:

Date.parse("2017-01-22 11:57:00")
1485115020000

The solution that worked for me was replacing the space in the dateString with "T". ( example : dateString.replace(/ /g,"T") )

Safari:

Date.parse("2017-01-22T11:57:00")
1485086220000

Chrome:

Date.parse("2017-01-22T11:57:00")
1485115020000

Note that the response from Safari browser is 8hrs (28800000ms) less than the response seen in Chrome browser because Safari returned the response in local TZ (which is 8hrs behind UTC)

To get both the times in same TZ

Safari:

Date.parse("2017-01-22T11:57:00Z")
1485086220000

Chrome:

Date.parse("2017-01-22T11:57:00Z")
1485086220000

How about hijack Date with fix-date? No dependencies, min + gzip = 280 B


I had the same issue.Then I used moment.Js.Problem has vanished.

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, then fall back to new Date(string) if a known format is not found.

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

e.g.

var date= moment(String);

use the format 'mm/dd/yyyy'. For example :- new Date('02/28/2015'). It works well in all browsers.


The same problem facing in Safari and it was solved by inserting this in web page

 <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script> 

Hope it will work also your case too

Thanks


As @nizantz previously mentioned, using Date.parse() wasn't working for me in Safari. After a bit of research, I learned that the lastDateModified property for the File object has been deprecated, and is no longer supported by Safari. Using the lastModified property of the File object resolved my issues. Sure dislike it when bad info is found online.

Thanks to all who contributed to this post that assisted me in going down the path I needed to learn about my issue. Had it not been for this info, I never would have probably figured out my root issue. Maybe this will help someone else in my similar situation.


convert string to Date fromat (you have to know server timezone)

new Date('2015-06-16 11:00:00'.replace(/\s+/g, 'T').concat('.000+08:00')).getTime()  

where +08:00 = timeZone from server


Arriving late to the party but in our case we were getting this issue in Safari & iOS when using ES6 back tick instead of String() to type cast

This was giving 'invalid date' error

const dateString = '2011-11-18';
const dateObj = new Date(`${dateString}`); 

But this works

const dateObj = new Date(String(dateString)); 

For me implementing a new library just because Safari cannot do it correctly is too much and a regex is overkill. Here is the oneliner:

console.log (new Date('2011-04-12'.replace(/-/g, "/")));

I use moment to solve the problem. For example

var startDate = moment('2015-07-06 08:00', 'YYYY-MM-DD HH:mm').toDate();

I am also facing the same problem in Safari Browser

var date = new Date("2011-02-07");
console.log(date) // IE you get ‘NaN’ returned and in Safari you get ‘Invalid Date’

Here the solution:

var d = new Date(2011, 01, 07); // yyyy, mm-1, dd  
var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss  
var d = new Date("02/07/2011"); // "mm/dd/yyyy"  
var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"  
var d = new Date(1297076700000); // milliseconds  
var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC 

Though you might hope that browsers would support ISO 8601 (or date-only subsets thereof), this is not the case. All browsers that I know of (at least in the US/English locales I use) are able to parse the horrible US MM/DD/YYYY format.

If you already have the parts of the date, you might instead want to try using Date.UTC(). If you don't, but you must use the YYYY-MM-DD format, I suggest using a regular expression to parse the pieces you know and then pass them to Date.UTC().


To have a solution working on most browsers, you should create your date-object with this format

(year, month, date, hours, minutes, seconds, ms)

e.g.:

dateObj = new Date(2014, 6, 25); //UTC time / Months are mapped from 0 to 11
alert(dateObj.getTime()); //gives back timestamp in ms

works fine with IE, FF, Chrome and Safari. Even older versions.

IE Dev Center: Date Object (JavaScript)

Mozilla Dev Network: Date


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to safari

How to Inspect Element using Safari Browser What does the shrink-to-fit viewport meta attribute do? background: fixed no repeat not working on mobile Swift Open Link in Safari How do I make flex box work in safari? onClick not working on mobile (touch) window.open(url, '_blank'); not working on iMac/Safari HTML5 Video tag not working in Safari , iPhone and iPad NodeJS/express: Cache and 304 status code Video auto play is not working in Safari and Chrome desktop browser