Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native method to inverse Date.toLocaleString convertion in JavaScript?

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?

like image 975
Daniel Avatar asked May 20 '18 08:05

Daniel


2 Answers

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);
like image 163
Matus Dubrava Avatar answered Sep 28 '22 03:09

Matus Dubrava


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.

like image 35
transistor09 Avatar answered Sep 28 '22 04:09

transistor09