Incorrect date being set with new Date() [duplicate] - javascript

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
When using the below line I am expecting the result to be '22/09/2017 14:05:43', however it is actually returning '09‎/‎10‎/‎2018‎ ‎14‎:‎05‎:‎43'.
var theDate = new Date('22/09/2017 14:05:43').toLocaleString();
I know there are js libraries out there such as moment.js that can be used for a lot of date time manipulation, but I was just wondering if anyone knew why this was happening and how I can get this to return the expected date?

Parsing of date strings is mostly implementation dependent, so it's generally recommended to avoid the built-in parser. Most browsers treat JavaScript dates with a pattern xx/xx/xxxx as MM/DD/YYYY, so 22/09/2017 is seen as either an invalid date (e.g. Safari, Firefox, Chrome), or the 9th day of the 22nd month of 2017 (apparently your browser).
Your browser is interpreting it as 'the 9th day of the 22nd month', so you're ending up on October 9th 2018, 22 months and 9 days into 2017.
To resolve this, you can separate the string into parts and give them to the constructor, avoiding the built-in parser (remembering to subtract 1 from the month number):
new Date(2017, 8, 22, ...)
Refer to MDN's Date documentation for more information.

Well the initial date string you passed to the Date constructor is wrong, it should be in the format 'MM/DD/YYYY HH:mm:ss'.
Your actual code will give Invalid Date:
var theDate = new Date('22/09/2017 14:05:43');
console.log(theDate);
var str = theDate.toLocaleString();
console.log(str);
Here 22 will be treated as a month and 09 will be treated as day. You need to fix it so it follows the Date standards:
var theDate = new Date('09/22/2017 14:05:43');
console.log(theDate);
var str = theDate.toLocaleString();
console.log(str);

Related

Convert Date to javascript format [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Parsing a string to a date in JavaScript
(35 answers)
Closed 2 years ago.
I am trying to convert this date into Mon Nov 26 2018 10:32:04 GMT (I am getting this data from the Api so i can't make changes to it)
I assume it is considering 26 as months thats why it is showing it as invalid date
Can Anyone help me with this. How to convert that date into the expected output i specified.
How to get
var d = new Date("26-11-2018 10:32:04")
return d; //Error: Invalid Date
expected Output: Mon Nov 26 2018 10:32:04 (IST)
Use moment.js to parse the date.
moment("26-11-2018 10:32:04", "DD-MM-YYYY HH-mm-ss").toDate()
Alternatively, if you really don't want to use moment for whatever reason, you can use regex magic.
new Date("26-11-2018 10:32:04".replace(/^(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)$/, "$3-$2-$1T$4:$5:$6Z"))
This is not a robust as #Yevgen answer but it also much simpler.
All I'm doing is removing the - and flipping the day and month values
const items = "26-11-2018 10:32:04".split('-')
new Date(`${items[1]} ${items[0]} ${items[2]}`)
This works for personal projects but I highly recommend using moment.js

Default year in Date if dateString does not have year part [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 6 years ago.
I was trying to check what values would return if partial values are sent.
var d = new Date("11/28");
console.log(d.toLocaleDateString())
I was expecting it to be 28th Nov., 2016(current year), but it returns 28th Nov., 2001.
So the question is Why is 2001 considered as default year?
2001 is not consider as default year.
This is a Chrome issue, if you run the same code with Firefox you get Invalid Date.
The language specification only includes rules for parsing ISO 8601 formatted strings. Parsing of any other format is implementation dependent (noting that the Date constructor and Date.parse are equivalent for parsing).
So given "11/28" is not a valid ISO 8601 string, the implementation is free to apply any heuristics it likes. Any result, including an invalid date, should be expected and consistency between implementations should not.

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

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.

JavaScript Date not working properly in IE8 [duplicate]

This question already has answers here:
Javascript JSON Date parse in IE7/IE8 returns NaN
(5 answers)
Closed 7 years ago.
Chrome showing result as expected but IE-8 giving NAN when i execute the following:
Chrome:
d = new Date("2014 12 01") // results Mon Dec 01 2014 00:00:00 GMT+0500 (Pakistan Standard Time)
IE-8:
d = new Date("2014 12 01") // results NaN undefined
The format you're trying to parse doesn't match the only specific format that new Date is required to parse. To parse it reliably cross-browser, you need to parse it explicitly — either in your own code, which can be trivially done with a regex, or using a library like MomentJS and telling it what the format is.
The trivial regex solution:
// NOTE! Uses local time.
var yourString = "2014 12 01";
var parts = yourString.match(/^(\d{4}) (\d{2}) (\d{2})$/);
if (parts) {
var date = new Date(+parts[1], +parts[2] - 1, +parts[3]);
alert(date.toString());
}

Javascript Date string constructing wrong date [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Hi I am trying to construct a javascript date object with a string, but it keeps contructing the wrong day. It always constructs a day that is one day behind. Here is my code
var date = new Date('2006-05-17');
The date i want to get is
Wednesday May 17 2006 00:00:00 GMT-0700 (PDT)
But instead I get
Tue May 16 2006 17:00:00 GMT-0700 (PDT)
When you pass dates as a string, the implementation is browser specific. Most browsers interpret the dashes to mean that the time is in UTC. If you have a negative offset from UTC (which you do), it will appear on the previous local day.
If you want local dates, then try using slashes instead, like this:
var date = new Date('2006/05/17');
Of course, if you don't have to parse from a string, you can pass individual numeric parameters instead, just be aware that months are zero-based when passed numerically.
var date = new Date(2006,4,17);
However, if you have strings, and you want consistency in how those strings are parsed into dates, then use moment.js.
var m = moment('2006-05-17','YYYY-MM-DD');
m.format(); // or any of the other output functions
What actually happens is that the parser is interpreting your dashes as the START of an ISO-8601 string in the format "YYYY-MM-DDTHH:mm:ss.sssZ", which is in UTC time by default (hence the trailing 'Z').
You can produce such dates by using the "toISOString()" date function as well.
http://www.w3schools.com/jsref/jsref_toisostring.asp
In Chrome (doesn't work in IE 10-) if you add " 00:00" or " 00:00:00" to your date (no 'T'), then it wouldn't be UTC anymore, regardless of the dashes. ;)
Remove the prepending zero from "05"

Categories

Resources