Neepsnikeep
Neepsnikeep

Reputation: 309

Date(string) shows different date and time using toLocaleString

I want to turn the string 1822-01-01 00:00:00 into a date by:

var d= new Date("1822-01-01 00:00:00");

What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.

See fiddle: https://jsfiddle.net/f1kLpfgd/

Javascript Date string constructing wrong date explains the wrong date with time zones. I have a different problem, as even minutes and seconds differ from my input. The solution using the new Date(1822, 0, 1, 0, 0, 0, 0) constructor does not work for me, as the result is 31.12.1821, 23:53:28.

Is it because the year is before 1901? But even 1899 works perfectly fine...

Update

For the formatting example custom VS toLocaleString, see updated fiddle: https://jsfiddle.net/f1kLpfgd/8/

Upvotes: 0

Views: 2612

Answers (2)

RobG
RobG

Reputation: 147403

I want to turn the string 1822-01-01 00:00:00 into a date by:

var d= new Date("1822-01-01 00:00:00");

What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.

Do not use the built-in parser for non-standard strings as whatever you get is implementation dependent and likely not what you expect in at least some hosts. In Safari, d will be an invalid date.

The format returned by toLocaleString is implementation dependent and varies between browsers. For me, new Date().toLocaleString() returns "9/21/2017, 9:48:49 AM", which is not consistent with the format typically used either in my locality or by users of the language I speak.

If you just want to reformat the string, see Reformat string containing date with Javascript.

If you want to know how to parse the string correctly, see Why does Date.parse give incorrect results?

If you want to format a Date, see Where can I find documentation on formatting a date in JavaScript?

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

If you don't want to use some library like date-fns , moment.js ...
To get the desired you could try like:

var dateString = "1822-01-01 00:00:00";

var d = new Date(dateString);
var formatted = d.getDate() +'.'+
                (d.getMonth()+1) +'.'+
                d.getFullYear() +', '+
                dateString.substr(11);

console.log(formatted);

Upvotes: 1

Related Questions