Why is 2/8888/2016 a valid date in IE and Firefox? - javascript

If you take the following:
var s = "2/8888/2016";
var d = new Date(s);
alert(d);
In Chrome, you'll get:
Invalid Date
But in IE and Firefox, you'll get:
Fri Jun 01 2040 00:00:00 GMT-0500 (Central Daylight Time)
It appears to be just adding 8888 days to Feb 01. Instead, I would expect the date to be considered invalid. Is there a way I can make FireFox and IE think this date string is invalid?

Short answer:
It's a misbehaviuor of the browsers you're mentioning.
You have to check date is in correct format on your own. But it's quite trivial, I suggest this approach:
Split the date in year y, month m, day d and create the Date object:
var date = new Date( y, m - 1, d ); // note that month is 0 based
Then compare the original values with the logical values obtained using the Date methods:
var isValid = date.getDate() == d &&
date.getMonth() == m-1 &&
date.getFullYear() == y;
Before doing all of this you may want to check if the date string is valid for any browser:
Detecting an "invalid date" Date instance in JavaScript
Long answer:
Firefox (and IE) accepting "2/8888/2016" as a correct string sate format seem to be a bug / misbehaviour.
In fact according to ECMAScript 2015 Language Specification when Date() is invoked with a single string argument should behave just as Date.parse()
http://www.ecma-international.org/ecma-262/6.0/#sec-date-value
The latter
attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16)
..that is specified here
http://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format
where you can read
The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
[...]
MM is the month of the year from 01 (January) to 12 (December).
DD is the day of the month from 01 to 31.
It seems that Firefox is interpreting the string value as when Date() is invoked with multiple arguments.
From
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.
This may explain how "2/8888/2016" turns into 2040-05-31T22:00:00.000Z

There's no way to make IE and FF think it's invalid, except:
you could change their javascript implementations
you use a library instead to deal with that.
We can also expect that Javascript, as a language, evolves and we can cross our fingers that browsers decide to follow a more strict specification. The problem of course is that every "fix" must be also backward compatible with previous versions of the language (does not happen always, Perl for example).
So the best thing by now is to use some library just like momentjs as suggested by Derek in the post comments.

You have stumbled across yet another reason why you should manually parse date strings.
When Date is provided a single string argument, it is treated as a date string and parsed according to the rules in Date.parse. The rules there first attempt to parse it as an ISO 8601 format string. If that doesn't work, it may fall back to any parsing algorithm it wants.
In the case of "2/8888/2016", browsers will first attempt to parse it as an ISO format and fail. It seems from experimentation that IE and Firefox determine that the string is in month/day/year format and effectively call the Date constructor with:
new Date(2016,1,8888);
However, other browsers may attempt to validate the values and decide that 8888 is not a valid date or month, so return an invalid date. Both responses are compliant with ECMA-262.
The best advice is to always manually parse date strings (a library can help, but generally isn't necessary as a bespoke parse function with validation is 3 lines of code) then you can be certain of consistent results in any browser or host environment.

Related

Date(string) shows different date and time using toLocaleString

I want to turn the string 1822-01-01 00:00:00 into a date by:
var d= new Date("1822-01-01 00:00:00");
What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.
See fiddle: https://jsfiddle.net/f1kLpfgd/
Javascript Date string constructing wrong date explains the wrong date with time zones. I have a different problem, as even minutes and seconds differ from my input. The solution using the new Date(1822, 0, 1, 0, 0, 0, 0) constructor does not work for me, as the result is 31.12.1821, 23:53:28.
Is it because the year is before 1901? But even 1899 works perfectly fine...
Update
For the formatting example custom VS toLocaleString, see updated fiddle: https://jsfiddle.net/f1kLpfgd/8/
If you don't want to use some library like date-fns , moment.js ...
To get the desired you could try like:
var dateString = "1822-01-01 00:00:00";
var d = new Date(dateString);
var formatted = d.getDate() +'.'+
(d.getMonth()+1) +'.'+
d.getFullYear() +', '+
dateString.substr(11);
console.log(formatted);
I want to turn the string 1822-01-01 00:00:00 into a date by:
var d= new Date("1822-01-01 00:00:00");
What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.
Do not use the built-in parser for non-standard strings as whatever you get is implementation dependent and likely not what you expect in at least some hosts. In Safari, d will be an invalid date.
The format returned by toLocaleString is implementation dependent and varies between browsers. For me, new Date().toLocaleString() returns "9/21/2017, 9:48:49 AM", which is not consistent with the format typically used either in my locality or by users of the language I speak.
If you just want to reformat the string, see Reformat string containing date with Javascript.
If you want to know how to parse the string correctly, see Why does Date.parse
give incorrect results?
If you want to format a Date, see Where can I find documentation on formatting a date in JavaScript?

JS Date() - Leading zero on days

A leading zero for the day within a string seems to break the Javascript Date object in Chrome. There are also some inconsistencies between browsers, since Firefox handles the leading zero correctly, but fails when the zero is not included. See this example: https://jsfiddle.net/3m6ovh1f/3/
Date('2015-11-01'); // works in Firefox, not in Chrome
Date('2015-11-1'); // works in Chrome, not in Firefox
Why? Is there a good way to work around/with the leading zero?
Please note, the strings are coming from MySQL via AJAX and all dates will contain the leading zero, and I can fix this by formating the dates server-side. What format would work the best?
EDIT
Just to specify what my problem was, it looks like Chrome is applying a time zone to the YYYY-MM-DD format, which reverts the Nov. 1st date back to the Oct. 31st date (because of my EDT local time).
According to ECMA-262 (5.1):
The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
The date/time string format as described in 15.9.1.15 is YYYY-MM-DDTHH:mm:ss.sssZ. It can also be a shorter representation of this format, like YYYY-MM-DD.
2015-11-1 is not a valid date/time string for Javascript (note it's YYYY-MM-D and not YYYY-MM-DD). Thus, the implementation (browser) is able to do whatever it wants with that string. It can attempt to parse the string in a different format, or it can simply say that the string is an invalid date. Chrome chooses the former (see DateParser::Parse) and attempts to parse it as a "legacy" date. Firefox seems to choose the latter, and refuses to parse it.
Now, your claim that new Date('2015-11-01') doesn't work in Chrome is incorrect. As the string conforms to the date/time string format, Chrome must parse it to be specification compliant. In fact, I just tried it myself -- it works in Chrome.
So, what are your options here?
Use the correct date/time format (i.e. YYYY-MM-DD or some extension of it).
Use the new Date (year, month, date) constructor, i.e. new Date(2015, 10, 1) (months go from 0-11) in this case.
Whichever option is up to you, but there is a date/time string format that all specification compliant browsers should agree on.
As an alternative, why not use unix timestamps instead? In JavaScript, you would would multiply the timestamp value by 1000,
e.g
var _t = { time: 1446220558 };
var _d = new Date( _t.time*1000 );
Test in your browser console:
new Date( 14462205581000 );
// prints Fri Oct 30 2015 11:55:58 GMT-0400 (EDT)
There's a little benefit in it as well (if data comes via JS) - you'd save 2 bytes on every date element '2015-10-30' VS 1446220558 :)

is there any workaround for broken v8 date parser?

V8 Date parser is broken:
> new Date('asd qw 101')
Sat Jan 01 101 00:00:00 GMT+0100 (CET)
I can use fragile regular expression like this:
\d{1,2} (jan|feb|mar|may|jun|jul|aug|sep|oct|nov|dec) \d{1,4}
but it is too fragile. I cannot rely on new Date (issue in V8) and also moment cant help me because moment is getting rid off date detection (github issue-thread).
is there any workaround for broken v8 date parser?
To be clear. We have Gecko and V8, both have Date. V8 has broken Date, Gecko has working one. I need the Date from in Gecko (Firefox).
Update: It’s definitely broken parser https://code.google.com/p/v8/issues/detail?id=2602
nope, Status: WorkingAsIntended
Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC and have the following constructors
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
From the docs,
dateString in new Date(dateString) is a string value representing a date. The string should be in a
format recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
Now looking at the v8 sourcecode in date.js:
function DateConstructor(year, month, date, hours, minutes, seconds, ms) {
if (!%_IsConstructCall()) {
// ECMA 262 - 15.9.2
return (new $Date()).toString();
}
// ECMA 262 - 15.9.3
var argc = %_ArgumentsLength();
var value;
if (argc == 0) {
value = %DateCurrentTime();
SET_UTC_DATE_VALUE(this, value);
} else if (argc == 1) {
if (IS_NUMBER(year)) {
value = year;
} else if (IS_STRING(year)) {
// Probe the Date cache. If we already have a time value for the
// given time, we re-use that instead of parsing the string again.
var cache = Date_cache;
if (cache.string === year) {
value = cache.time;
} else {
value = DateParse(year); <- DOES NOT RETURN NaN
if (!NUMBER_IS_NAN(value)) {
cache.time = value;
cache.string = year;
}
}
}
...
it looks like DateParse() does not return a NaN for for a string like 'asd qw 101' and hence the error. You can cross-check the same with Date.parse('asd qw 101') in both Chrome(v8) [which returns -58979943000000] and Gecko (Firefox) [which returns a NaN]. Sat Jan 01 101 00:00:00 comes when you seed new Date() with a timestamp of -58979943000000(in both browsers)
is there any workaround for broken v8 date parser?
I wouldnt say V8 date parser is broken. It just tries to satisfy a string against RFC 2822 standard in the best possible way but so does gecko and both break gives different results in certain cases.
Try new Date('Sun Ma 10 2015') in both Chrome(V8) and Firefox(Gecko) for another such anomaly.
Here chrome cannot decide weather 'Ma' stands for 'March' or 'May' and gives an Invalid Date while Firefox doesnt.
Workaround:
You can create your own wrapper around Date() to filter those strings that V8's own parser cannot. However, subclassing built-ins in ECMA-5 is not feasible. In ECMA-6, it will be possible to subclass built-in constructors (Array, Date, and Error) - reference
However you can use a more robust regular expression to validate strings against RFC 2822/ISO 8601
^(?:(?:31(\/|-|\. |\s)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.|\s)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.|\s)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.|\s)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
Image generated from debuggex
So, seems like v8 aint broken, it just works differently.
Hope it helps!
You seem to be asking for a way to parse a string that might be in any particular format and determine what data is represented. There are many reasons why this is a bad idea in general.
You say moment.js is "getting rid of date detection", but actually it never had this feature in the first place. People just made the assumption that it could do that, and in some cases it worked, and in many cases it didn't.
Here's an example that illustrates the problem.
var s = "01.02.03";
Is that a date? Maybe. Maybe not. It could be a section heading in a document. Even if we said it was a date, what date is it? It could be interpreted as any of the following:
January 2nd, 2003
January 2nd, 0003
February 1st, 2003
February 1st, 0003
February 3rd, 2001
February 3rd, 0001
The only way to disambiguate would be with knowledge of the current culture date settings. Javascript's Date object does just that - which means you will get a different value depending on the settings of the machine where the code is running. However, moment.js is about stability across all environments. Cultural settings are explicit, via moment's own locale functionality. Relying on the browser's culture settings leads to errors in interpretation.
The best thing to do is to be explicit about the format you are working with. Don't allow random garbage input. Expect your input in a particular format, and use a regex to validate that format ahead of time, rather then just trying to construct a Date and seeing if it's valid after the fact.
If you can't do that, you'll have to find additional context to help decide. For example, if you are scraping some random bits of the web from a back-end process and you want to extract a date from the text, you'd have to have some knowledge about the language and locale of each particular web page. You could guess, but you'd likely be wrong a fair amount of the time.
See also: Garbage in, garbage out
ES5 15.9.4.2 Date.parse: /.../ If the String does not conform to
that format the function may fall back to any implementation-specific
heuristics or implementation-specific date formats. Unrecognizable
Strings or dates containing illegal element values in the format
String shall cause Date.parse to return NaN.
So that's all right and according to the citation above result of v8 date parser:
new Date('asd qw 101') : Sat Jan 01 101 00:00:00 GMT+0100
(CET)
new Date('asd qw') : Invalid Date

Why does a string of numbers work differently than actual numbers in a new Date?

Why does a string of numbers work differently than actual numbers in a new Date():
var myfirstDate = new Date("2013, 10, 15"); //returns Tue Oct 15 2013 00:00:00 GMT-0500 (CDT)
var mysecondDate = new Date(2013, 9, 15); // also returns Tue Oct 15 2013 00:00:00 GMT-0500 (CDT)
myfirstDate.value == mysecondDate.value; //returns true
I looked at several tutorials and the idea of having a string like myfirstDate above isn't even mentioned. Does javascript automatically parse the string?
See the docs.
You're effectively invoking two different constructors.
The first one is parsed as a human-readable date:
new Date(dateString)
The second one expects 3 or more parameters, providing a year, a 0-based month number, and a day
new Date(year, month, day [, hour, minute, second, millisecond]);
year
Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998, rather than 98.
month
Integer value representing the month, beginning with 0 for January to 11 for December.
day
Integer value representing the day of the month (1-31).
Until ES5, parsing of date strings was entirely implementation dependent, though there were one or two strings that were consistently parsed by several browsers. ES5 introduced parsing of a version of ISO8601, however it's not supported by all browsers in use.
It is best to manually parse date string to ensure they are correct. There are various libraries to assist with that, but it isn't difficult (2 lines of code).
Incidentally, there is no Date.prototype.value method, so likely you are comparing undefined with itself. You should be comparing the time value, so:
myfirstDate.getTime() == mysecondDate.getTime();
or just:
myfirstDate == mysecondDate;
Oh, to answer the question: when the Date function is called as a constructor with a single string argument, it is treated as a date string and parsed (see above). So "10" represents October.
When Date is called as a constructor with more than one argument, they are treated as date values so 9 is treated as October since month arguments are zero indexed (0=January, 1=February, etc.).

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.
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, "/")));
The pattern yyyy-MM-dd isn't an officially supported format for Date constructor. Firefox seems to support it, but don't count on other browsers doing the same.
Here are some supported strings:
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
DateJS seems like a good library for parsing non standard date formats.
Edit: just checked ECMA-262 standard. Quoting from section 15.9.1.15:
Date Time String Format
ECMAScript defines a string
interchange format for date-times
based upon a simplification of the ISO
8601 Extended Format. The format is
as follows: YYYY-MM-DDTHH:mm:ss.sssZ
Where the fields are as follows:
YYYY is the decimal digits of the year in the Gregorian calendar.
"-" (hyphon) appears literally twice in the string.
MM is the month of the year from 01 (January) to 12 (December).
DD is the day of the month from 01 to 31.
"T" appears literally in the string, to indicate the beginning of
the time element.
HH is the number of complete hours that have passed since midnight as two
decimal digits.
":" (colon) appears literally twice in the string.
mm is the number of complete minutes since the start of the hour as
two decimal digits.
ss is the number of complete seconds since the start of the minute
as two decimal digits.
"." (dot) appears literally in the string.
sss is the number of complete milliseconds since the start of the
second as three decimal digits. Both
the "." and the milliseconds field may
be omitted.
Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-"
followed by a time expression hh:mm
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes time-only forms with
an optional time zone offset appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
Also included are "date-times" which
may be any combination of the above.
So, it seems that YYYY-MM-DD is included in the standard, but for some reason, Safari doesn't support it.
Update: after looking at datejs documentation, using it, your problem should be solved using code like this:
var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");
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
I use moment to solve the problem.
For example
var startDate = moment('2015-07-06 08:00', 'YYYY-MM-DD HH:mm').toDate();
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
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
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);
For people using date-fns we can parseISO date and use it to format
Invalid
import _format from 'date-fns/format';
export function formatDate(date: string, format: string): string {
return _format(new Date(date), format);
}
This function on safari throw error with Invalid date.
Solution
To fix it we should use:
import _format from 'date-fns/format';
import _parseISO from 'date-fns/parseISO';
export function formatDate(date: string, format: string): string {
return _format(_parseISO(date), format);
}
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().
How about hijack Date with fix-date? No dependencies, min + gzip = 280 B
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
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.
For me the issue was I forgot to add 0 before the single digit month or day in YYYY-MM-DD format.
What I was parsing: 2021-11-5
What it should be: 2021-11-05
So, I wrote a little utility which converts YYYY-M-D to YYYY-MM-DD i.e. 2021-1-1 to 2021-01-01:
const date = "2021-1-1"
const YYYY = date.split("-")[0];
//convert M->MM i.e. 2->02
const MM =
date.split("-")[1].length == 1
? "0" + date.split("-")[1]
: date.split("-")[1];
//convert D->DD i.e. 2->02
const DD =
date.split("-")[2].length == 1
? "0" + date.split("-")[2]
: date.split("-")[2];
// YYYY-MM-DD
const properDateString = `${YYYY + "-" + MM + "-" + DD}`;
const dateObj = new Date(properDateString);
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.
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));
In my case, it wasn't the formatting, it was because in my backend Node.js Model, I was defining the database variable as a String instead of a Date.
My backend Node Database Model said:
starttime:{
type: String,
}
instead of the correct:
starttime:{
type: Date,
}
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
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
use the format 'mm/dd/yyyy'. For example :- new Date('02/28/2015'). It works well in all browsers.
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.

Categories

Resources