javascript date.parse difference in chrome and other browsers - javascript

I have a date string "2011-11-24T09:00:27+0000" fetched from the graph.facebook API.
When I run
var timestamp = Date.parse(facebookDate);
in chrome. I get a timestamp that relates to the date! perfect!
But in EVERY other major browser... I get "NaN" !!! ?
Surely all these browsers use the same javascript parse function right?
Can anybody explain why the same javascript function give different results?
And can anybody also tell me how to fix this issue...
Thanks in advance
Alex

Here is a fix for Firefox and IE/Safari (with the help from JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse
) :
DEMO
var noOffset = function(s) {
var day= s.slice(0,-5).split(/\D/).map(function(itm){
return parseInt(itm, 10) || 0;
});
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
var offsetString = s.slice(-5)
var offset = parseInt(offsetString,10)/100;
if (offsetString.slice(0,1)=="+") offset*=-1;
day.setHours(day.getHours()+offset);
return day.getTime();
}
From MDN
JavaScript 1.8.5 note
A subset of ISO 8601 formatted date strings can now also be parsed.
Alternatively, the date/time string may be in ISO 8601 format. Starting with JavaScript 1.8.5 / Firefox 4, a subset of ISO 8601 is supported. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00 (date and time) can be passed and parsed. Timezones in ISO dates are not yet supported, so e.g. "2011-10-10T14:48:00+0200" (with timezone) does not give the intended result yet.

Related

Safari returns "invalid date" when parsing a YYYY-MM-DDTHH:MM:SS+0000 ISO time string

The API I am using, returns dates in a format like YYYY-MM-DDTHH:MM:SS+0200. When I try to create a Date object of that, it usually works:
new Date('2021-06-28T12:00:00+0200');
However, some users with an older version of Safari/iOS complain, that they get some "Invalid Date", which I cannot recreate because all my devices are up to date.
How can I fix the date parsing so that it works across all browsers? Is the date string incorrect? Is the parsing incorrect?
How can I test if it actually does? Because as I said, it already seems to be working on alle the devices I have access to, but unfortunately it doesn’t on some devices I don’t have access to...
Thank you very much!
I'd suggest using a library such as luxon for parsing dates. It should handle both +hhmm and +hh:mm UTC offsets.
You can parse to a luxon DateTime, then simply call .toJSDate() to get a Date, this should mean minimal code changes:
let { DateTime } = luxon;
console.log("Using +hhmm UTC offset:");
let input = '2021-06-28T12:00:00+0200';
let d = (DateTime.fromISO(input));
console.log('Input:', input)
console.log('toJSDate:', d.toJSDate())
console.log('ISO time (Local):', d.toISO())
console.log("\nUsing +hh:mm UTC offset:");
input = '2021-06-28T12:00:00+02:00';
d = (DateTime.fromISO(input));
console.log('Input:', input)
console.log('toJSDate:', d.toJSDate())
console.log('ISO time (Local):', d.toISO())
<script src="https://moment.github.io/luxon/global/luxon.js"></script>

javascript: IE alternative to convert ISO to local time

I am trying to convert ISO time local time.
here is my code :
var local_date = new Date('2018-09-11T06:22:39.000-0400');
local_date.toLocaleDateString();
local_date.toLocaleTimeString();
this code is working fine in chrome but in IE its giving error.
first line of code gives me Invalid Date
Looking for a fix which works in all browsers.
FYI: I do not want to use moment.js or any other library, want it in vanilla javascript.
So, the problem is your date-string format.
By reading the Mozilla documentation about the Date Object we can see that your string has to follow the IETF-compliant RFC 2822 timestamps and the ISO8601.
If we open the second one (the ISO8601) we can see that the accepted format is YYYY-MM-DDTHH:mm:ss.sssZ where the Z may be (+|-)HH:mm.
So instead of new Date('2018-09-11T06:22:39.000-0400'); if we execute new Date('2018-09-11T06:22:39.000-04:00'); it works.
If you don't want to add it manually, you can do it automatically by using the splice method from this answer and the code:
// A nice Polyfill
if (!String.prototype.splice) {
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
// Your code
var dateString = '2018-09-11T06:22:39.000-0400'.splice(26, 0, ":");
var local_date = new Date(dateString);
local_date.toLocaleDateString();
local_date.toLocaleTimeString();
I don't claim that 2018-09-11T06:22:39.000-0400 is in an invalid format, but an unaccepted by the IE.
Also, if you want to vanilla javascript you should stop opening IE at all.

Get GMT time for date and time

I have a string in GMT "2017-01-17 00:00:00.000" and I want to get time and date differently (the string does not have to be in that format).
I tried:
var datetime = new Date(calEvent.start);
var date = datetime.toLocaleDateString(); //output: 1/16/2017
var time = datetime.toLocaleTimeString(); //output: 4:00:00 PM
but the output for date and time I want should be in GMT timezone. Anyone know how to do that without using substring for string?
Thanks
The string "2017-01-17 00:00:00.000" is not consistent with the subset of ISO 8601 specified in ECMA-262 and will not be parsed correctly in some browsers. As it is, it will be treated as local if parsed at all.
You can modify the string by adding a "T" between the date and time and a trailing "Z" for UTC, then let the Date constructor parse it, e.g.
var s = '2017-01-17 00:00:00.000';
var d = new Date(s.replace(' ', 'T') + 'Z');
console.log(d);
Which will work in most modern browsers, however it will fail in older browsers like IE. You can also write a small function to parse the strting as UTC:
function parseAsUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1] - 1, b[2], b[3], b[4], b[5], b[6]));
}
console.log(parseAsUTC('2017-01-17 00:00:00.000'));
You can also use one of the various libraries available, however if all you need it to parse one particular format, then that's not necessary.
NOTE:
It's generally not recommended to parse strings with the Date constructor (or Date.parse) as they are largely implementation dependent, however the ISO 8601 extended format is now fairly well supported and is specified in ECMA-262.
The time zone must be specified with upper case "Z". Firefox (at least) will generate an invalid date if "z" is used.

JavaScript on IE and Firefox

I have this very simple function that doesnt work on Firefox or IE. Just wondering if you have some insight.
function compareDates(obj, fecha){
var date1 = new Date( Date.parse(obj.value.replace(/-/g, " ")) );
var date2 = new Date( Date.parse(fecha.value.replace(/-/g, " ")) );
if(date1 < date2){
alert("Invalid Date");
}
}
This function receives a 10-JUL-13 and a 20-JUL-13, for examples.
In IE, I don't get the alert, in Chrome, I do get the alert. Please see http://jsfiddle.net/ZDtVv/
Date.parse requires an ISO date, which requires the full year. Chrome and Firefox try to figure it out for you, you shouldn't rely on that.
// This works
compareDates({value: '10-JUL-2013'}, {value: '20-JUL-2013'})
See http://jsfiddle.net/ZDtVv/1/
Those date strings are not valid date strings, so you get Date objects that have NaN as their actual timestamp. And NaN < NaN tests false.
Per spec, behavior for invalid date strings is undefined; a JavaScript implementation can turn them into NaN or use whatever heuristics it wants to for parsing them. For example, those dates could be year 13 or year 1913 or year 1413 and those would all be valid behaviors per spec.

Javascript Date(dateString) returns NaN on specific server and browser

I'm using the Javascript Date(string) constructor with a date format of "yyyy-mm-dd". The constructor works just fine in IE 9 and Firefox unless the app is running on our testing VM which is running IIS. If it's on the VM, in IE 9 it returns 'NaN', but still works normally in Firefox.
var dateAsString = "2011-11-09";
var dateCreated = new Date(dateAsString);
I was under the assumption that the server had nothing to do with client-side Javascript. Any suggestions?
And for those of us who want to know how to replace hyphens (aka dashes) with slashes:
new Date(dashToSlash(string));
That uses this function:
function dashToSlash(string){
var response = string.replace(/-/g,"/");
//The slash-g bit says: do this more than once
return response;
}
In my case it's much easier to convert hyphens to slashes selectively (only where it's needed for the Date() function) than to replace the date format everywhere in my code.
Note: you really need to define a separate 'response' variable and assign it the value of the replace operation result. If you don't, the string is returned unaltered in Chrome. That's not a huge problem, since Chrome doesn't have a problem with hyphenated date strings to begin with. But still...
Just use slashes instead of hyphens if you can.
EDIT: Expanded clarification...
The ISO 8601 standard format uses the hyphen as a date separator. My answer does not mean you do not need to follow standards. You can use slashes only for the Date constructor if necessary.
It's because of the date format. For some reason, IE and Safari get tripped up with yyyy-mm-dd. Use another date format and you should be all set.
It's talked about here:
http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari
I suggest attempting a more reliable form of date parsing. The example below uses setFullYear(). Does IE produce a different result with the code below?
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* #param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* #return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
Source: http://jibbering.com/faq/#parseDate

Categories

Resources