5

We have date converted to locale string. For example:

x = (new Date()).toLocaleString()

and x has value

"20.05.2018, 10:21:37"

How to process this string to Date object.

I was tried

new Date(x)
Invalid Date

and

Date.parse(x)
NaN

It is possible and simple to do without external libraries like moment.js?

Daniel
  • 7,684
  • 7
  • 52
  • 76
  • [Why does parsing a locale date string result in an invalid date?](https://stackoverflow.com/questions/29988868/why-does-parsing-a-locale-date-string-result-in-an-invalid-date) – deEr. May 20 '18 at 08:38
  • You don't need to parse again the stringified date, just store date in a variable `date`and use it: `date = new Date(); dateStr = date.toLocaleString();` – Alejandro Blasco May 20 '18 at 08:41
  • What implementation produces that output? – RobG May 20 '18 at 21:39

2 Answers2

4

You can parse it on your own.

const date = "20.05.2018, 10:21:37";
const [first, second] = date.split(',').map(item => item.trim());
const [day, month, year] = first.split('.');
const [hours, minutes, seconds] = second.split(':');

const newDate = new Date(year, month - 1, day, hours, minutes, seconds);
console.log(newDate);

Or using regex

const date = "20.05.2018, 10:21:37";
const m = /^(\d{2})\.(\d{2})\.(\d{4}), (\d{2}):(\d{2}):(\d{2})$/.exec(date);
const newDate = new Date(m[3], m[2] - 1, m[1], m[4], m[5], m[6]);
console.log(newDate);
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
  • The split can be simplified using `dateString.split(/\D+/)` to get all the numeric values in one go, so `let [d,m,y,h,M,s] = "20.05.2018, 10:21:37".split(/\D+/); new Date(y,m-1,d,h,M,s)`. ;-) – RobG May 20 '18 at 21:44
2

It is possible to use Intl.DateTimeFormat.prototype.formatToParts() to get the format of the date without knowing it beforehand.

// should default to toLocaleDateString() format
var formatter = Intl.DateTimeFormat()
// I suggest formatting the timestamp used in
// Go date formatting functions to be able to 
// extract the full scope of format rules
var dateFormat = formatter.formatToParts(new Date(1136239445999))

On my machine dateFormat yields

[
    {type: "month", value: "1"},
    {type: "literal", value: "/"},
    {type: "day", value: "3"},
    {type: "literal", value: "/"},
    {type: "year", value: "2006"},
]

By iterating over this array it should be feasible to parse a string into parts and then fill them in a Date object.

transistor09
  • 4,828
  • 2
  • 25
  • 33