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
?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With