Date returns NaN in IE [duplicate] - javascript

Why cannot IE parse this string as a Date object.
var d = Date.parse("Fri Jun 11 04:55:12 +0000 2010"); // returns NaN
However, it works well in FireFox. I am running IE 8.
Thanks.

You are getting NaN value in IE 8 and its working in Firefox because the format of the string varies with browser and operating system.
For example, in IE6 for Windows XP, the string is in the following format:
Tue Dec 05 16:47:20 CDT 2006
But in Firefox for Windows XP, the string is
Tue Dec 05 2006 16:47:20 GMT-0500
to make it compatible with both browser you will have to first check the browser in your
javascript code and then accordingly give your input date string.

I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.
You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:
$.datepicker.parseDate('yy-mm-dd', '2007-01-26');

Is solved my problem by creating an date object and let me give it back the timestamp.
But for this you need to convert you string into this format:
year, month, date, hours, minutes, seconds,ms
an example would be like:
dateObj = new Date(year, month, date);
timestamp = dateObj.getTime();
This works save in IE and FF.
IE Dev Center: Date Object (JavaScript)
Mozilla Dev Network: Date
For your example you would to something like this:
//your string
var str = "Fri Jun 11 04:55:12 +0000 2010";
//maps months to integer from 0 to 11
var monthArray = {"Jan":0, "Feb":1, "Mar":2, "Apr":3, "May":4, "Jun":5, "Jul":6, "Aug":7, "Sep":8, "Oct":9, "Nev":10, "Dec":11};
//get the values from the string
var regex = /^[^ ]+ ([^ ]+) (\d{1,2}) (\d{2}):(\d{2}):(\d{2}) \+(\d{4}) (\d{4})$/;
match = regex.exec(str);
var month = monthArray[match[1]],
date = match[2],
hours = match[3],
minutes = match[4],
seconds = match[5],
ms = match[6],
year = match[7];
//create date object with values
var dateObject = new Date(year, month, date, hours, minutes , seconds, ms);
var ts = dateObject.getTime(); //timestamp in ms

Problem
In case your date is stored in SQL datetime like 2020-04-07 05:30:00 and want to parse it in IE. When you parse it with JavaScript in IE using new Date(), it outputs Invalid Date while latest versions of Chrome and Firefox parse this date correctly.
Solution
You have to replace <space> with T in datetime string coming from SQL.
Example
let myDate = '2020-04-07 05:30:00';
let myFormattedDate = myDate.replace(' ', 'T'); // '2020-04-07T05:30:00'
console.log(new Date(myFormattedDate));

because of the +00000. try to add that the last
var d = Date.parse("Fri Jun 11 04:55:12 2010 +0000");

This may help you. I just solved a problem similar to this.
Problem with Javascript Date function in IE 7, returns NaN

Related

Safari new Date with string value outs different time [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
What I am trying to do is changing "yyyy-mm-dd HH:mm:ss" string to date value.
Here is the current code
var c = new Date('2019-01-19 23:59:59'.replace(/\s+/g, 'T'))
It returns
chrome : Sat Jan 19 2019 23:59:59 GMT+0900 (KST)
safari : Sun Jan 20 2019 08:59:59 GMT+0900 (KST)
ie11 : Sat Jan 19 2019 23:59:59 GMT+0900 (KST)
What should I do to make it returns all same date?
Thanks.
Safari... It does not consider time zone offset when creates an instance with date string.
Add Z to the end is also good point, but if you want to get the same result with other browsers, should calculate timezone offset.
Here is what I have done ...
// Before do this, check navigator.userAgent
// and execute below logic if it is desktop Safari.
// Add Z is the convention, but you won't get any error even if do not add.
var c = new Date('2019-01-19 23:59:59Z'.replace(/\s+/g, 'T'))
// It will returns in minute
var timeOffset = new Date().getTimezoneOffset();
// Do not forget getTime, if not, you will get Invalid date
var d = new Date(c.getTime() + (timeOffset*60*1000))
Will open this post till tomorrow for waiting better answer.
Thanks.
Add the 'Z' to the date string for GMT/UTC timezone
var c = new Date('2019-01-19 23:59:59'.replace(/\s+/g, 'T')+'Z');
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ):
Date and time is separated with a capital T.
UTC time is defined with a capital letter Z.
If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM instead:
for example
var d = new Date("2019-01-19T23:59:59-09:00");

why I can't create a new Date() from given string?

I'm using moment.js to find a time in different timestamp.
I wrote a simple javascript:
$(function () {
var timestamp = 1443556318; //GMT Tue, 29 Sep 2015 19:51:58 GMT
var today2 = moment.unix(timestamp).tz('America/New_York').toString();
today = new Date(today2);
alert(today2);
alert(today);
var hh = today.getHours();
alert(hh); //why it shows me 21 instead of 15?
});
and seems like this line today = new Date(today2); does not work properly.
Can you help me with that?
http://jsfiddle.net/b8o5cvdz/3
It doesn't work because, you use the following constructor
new Date(dateString);
where the
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).
If you want to all the possible constructors, please have a look here.

Date parse - Invalid date for some data

I am looking to parse the below date format in JavaScript but I am struggling to make it work reliably.
//Works
var a = new Date("Thu, Nov 7 12:59:45 GMT 2013")
alert(a)
//Invalid date
var b = new Date("Tue, Jun 19 11:14:23 BST 2012")
alert(b)
What is a reliable method of parsing this date format?
I am testing in FireFox 36.
Found that the parsing will automatically associate the timezone if I remove it
var b = new Date("Tue, Jun 19 11:14:23 BST 2012".replace("BST",""))
I would prefer it to just work but meh

Best way to remove 'EDT' from a date returned via javascript with toLocaleString()

I'm relatively new to javascript, so this may be a really simple question. Is there an easy way to stop 'EDT' from printing after a date returned with toLocaleString?
Thanks!
There is no way to be certain what toLocaleString will return; you certainly couldn't guarantee EDT would show up on every machine that runs it, let alone any indication of timezone.
From Mozilla's developer network:
The toLocaleString method relies on the underlying operating system in formatting dates. It converts the date to a string using the formatting convention of the operating system where the script is running. For example, in the United States, the month appears before the date (04/15/98), whereas in Germany the date appears before the month (15.04.98). If the operating system is not year-2000 compliant and does not use the full year for years before 1900 or over 2000, toLocaleString returns a string that is not year-2000 compliant. toLocaleString behaves similarly to toString when converting a year that the operating system does not properly format.
One possible workaround would be to construct a custom date string using toLocaleDateString and toLocaleTimeString.
// Something to this effect:
var d = new Date();
console.log(d.toLocaleDateString() + " " + d.toLocaleTimeString());
This generally wouldn't include the time zone in its output, but even this isn't perfect as you can't know what the exact format of the output would be.
Thus, the best solution would be to use a custom date-formatting function:
// Add leading-zeros to numbers less than 10[000...]
function padZ(num, n) {
n = n || 1; // Default assume 10^1
return num < Math.pow(10, n) ? "0" + num : num;
}
function formattedDate(d) {
var day = d.getDate();
var month = d.getMonth() + 1; // Note the `+ 1` -- months start at zero.
var year = d.getFullYear();
var hour = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
return month+"/"+day+"/"+year+" "+hour+":"+padZ(min)+":"+padZ(sec);
}
For an in-depth look at the available Date methods, check out Date on the MDN.
As far as I can tell, no browser returns 'EDT' from toLocaleString, on windows anyway,
and only Chrome returns the timezone at all.
Other platforms may assign the string differently.
My bigger beef is that Chrome uses a 24 hour clock for local time.
// testing new Date().toLocaleString() (windows 7)
Safari 5.0>> Tuesday, June 14, 2011 15:13:43
Chrome 9.0.597.98>> Tue Jun 14 2011 15:15:01 GMT-0400 (Eastern Daylight Time)
Opera 11.01>> 6/14/2011 3:15:37 PM
Firefox 4.0.1>> Tuesday, June 14, 2011 3:16:33 PM
MSIE 8.0>> Tuesday, June 14, 2011 3:16:06 PM
MSIE 9.0>> Tuesday, June 14, 2011 3:17:09 PM
They all return the hours:minutes:seconds in a group,
so to exclude anything after the time you could:
var d=new Date().toLocaleString();
var s= d.toLocaleString().match(/^[^:]+(:\d\d){2} *(am|pm)\b/i)[0];
returned value: (Chrome)
Tue Jun 14 2011 15:26:11:11
Another way is to concat the locale day and time strings, which, surprisingly, does not return the timezone on chrome- but your milage may vary.
var D=new Date();
D.toLocaleDateString()+' '+D.toLocaleTimeString()
returns Tuesday, June 14, 2011 15:44:35 in Chrome
var dateWithoutTimeZone = function() {
return new Date().toLocaleString().replace(/\s*\(?EDT\)?/, '');
};
dateWithoutTimeZone(); // => "Tue Jun 14 2011 2:58:04 GMT-0400"
Is the time zone always at the end of the string? (The time zone doesn't appear at all when I try.)
If it is, you can use the slice method to remove the last four characters of the string (space + 3-character time zone).
document.write(mydate.toLocaleString().slice(0,-4));

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