'Javascript .toLocaleString() returns wrong month?
I’m at a loss here. I need to display a JavaScript date in my locale, but the displayed locale string is off by 1 month in the future.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var d = new Date(2018,4,3,21,0);
document.getElementById("demo").innerHTML = d.toLocaleString('de-DE');
</script>
</body>
</html>
The displayed result is 3.5.2018, 21:00:00
instead of 3.4.2018, 21:00:00
. It works correctly if I try Date.now()
instead.
Tested on both Ubuntu 14.04.5 and Linux Mint 17.3, with Firefox 59.0.2 (64-Bit) and Chromium 65.0.3325.181.
If I’m not overlooking something, I consider this a serious bug, but before filing an issue (where?) I thought I’d ask here.
Thanks for any input on this matter!
Solution 1:[1]
Js new Date() starts counting Month from 0 to 11.
When, you are entering new Date(2018,4,3)
It's been calculated as 3-May-2018.
And, the output is 3/5/2018.
Solution 2:[2]
The month parameter in the Date()
constructor is 0-based.
You may find this helpful:
The argument month is 0-based. This means that January = 0 and December = 11. - Date - JavaScript | MDN
Solution 3:[3]
display Date in my locale Machin and Next Months
var d = new Date();
d.setMonth(d.getMonth() +1);
console.log(d.toLocaleDateString("de-DE", { month: 'long' }));
return d.toLocaleDateString("de-DE", { month: 'long' })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Prasanta Bose |
Solution 2 | D. Pardal |
Solution 3 | Ardalan |