javascript: IE alternative to convert ISO to local time - javascript

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.

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 milliseconds notaion was not working in firefox

Can anyone help me with this ?
var current_date=new Date('2012/12/21 22:59:59.997');
var result=current_date.getTime();
Im not getting result in Firefox but it does show in chrome, in FF it shows invalid date.
You should be able to do the following (using date.setMilliseconds):
var dateString = '2012/12/21 22:59:59.997';
var dateStringSplit = dateString.split('.');
var myDate = new Date(dateStringSplit[0]);
myDate.setMilliseconds(dateStringSplit[1]);
console.log(myDate);
Firefox and some other browsers (namely, Safari or Opera) don't like milliseconds.
// Split off the part after the dot
var current_date = new Date('2012/12/21 22:59:59.997'.split('.')[0]);
// Works everywhere!
var result = current_date.getTime();
If you really want to work with milliseconds, you have to split the date in multiple parts and use new Date() with those. From MDN documentation, here are the options:
new Date(year, month, day [, hour, minute, second, millisecond])
Or, as h2ooooooo says, you can use the second part of the split date and use setMilliseconds.
Overall, you have plenty of solutions. Choose the one that annoys you the least.
The format you are using is not a standard format for Date.parse
You may want to split the string and set the parts individually. Also, please manage the time zone correctly as it is not apparent which timezone the date string is in.

What is needed for a valid Javascript Date object?

I've been banging my head over this one all day. No matter how I initialize a Javascript Date I cannot seem to get a valid Date object... I'm assuming the Date is invalid and not working properly by inspecting it with Chrome's debugger, which has the value '__proto__: Invalid Date'.
I've tried all of the following:
var d = new Date();
var d = new Date('2012-10-08');
var d = new Date('2012-10-08 00:00:00');
var d = new Date(Date('2012-10-08'));
var d = new Date(Date.parse('2012-10-08'));
var d = new Date(2012,10,08);
var d = new Date("October 13, 1975 11:13:00");
Along with countless other attempts.
This is presenting a problem in iOS where I'm trying to get values from these Date objects but every function just returns NaN. I'd prefer to avoid having to use external libraries or have to convert YYYY-MM-DD format into any other format since I'm trying to get this to work with an HTML5 input type="date" with minimal code for a mobile site.
Essentially this boils down to: What are the parameters that make a Date object valid?!
Do not trust the Date object to parse strings, you must do it manually. Given the format 2012-10-08,
function stringToDate(s) {
s = s.match(/\d+/g);
if (s) {
return new Date(s[0], --s[1], s[2]);
}
}
You may want to do some validation of the input string and the resulting date object, the above just shows the conversion.
Edit
BTW, the only string format that seems to be parsed consistently in all browsers is the US-specific month/date/year format. There is no specification to support its use, nor is there any reason to believe browsers will continue to support it other than pragmatism and "legacy" reasons.
For the vast majority of regions, '2/3/2012' is interpreted as 2 March, so getting 3 February might be unexpected.
Once older versions of IE are no longer in use (probably a few years yet), it should be safe to use the ISO8601 extended format per ECMA-262. However, even browsers that support it are inconsitent. e.g given:
new Date('2011-02-29');
Firefox 15 returns 'Invalid Date', IE 9 and Chrome 22 return a date object for 1 March, 2011.
There are three ways of calling the method:
The number of milliseconds from the epoch:
new Date(milliseconds)
Any IETF-compliant RFC 2822 timestamp:
new Date("November 2, 1988 10:00:00");
Individual args:
new Date(year, month, day [, hour, minute, second, millisecond])
new Date(1988,11,02,10,0,0);
If your main concern is about parsing, have a look at Moment.js which is clearly superior to parsing things yourself. (IMHO)
Turns out jQuery doesn't bind the .change() event to input type="date" properly in iOS. Changed the event to .blur() and everything seems to work now. However, it still seems it is impossible to create a valid date object in Chrome... an issue for another day.
Thanks for the help everyone!

javascript date.parse difference in chrome and other browsers

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.

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