How to convert string like '01-01-1970 00:03:44'
to datetime?
Advertisement
Answer
For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date
. It may bite you, because of browser compatibility problems.
tryParseDateFromString
is ES6 utility method to parse a date string using a format string parameter (format
) to inform the method about the position of date/month/year in the input string. The date is constructed using Date.UTC
, circumventing the aforementioned browser compatibility problems.
JavaScript
x
55
55
1
// fixed format dd-mm-yyyy
2
function dateString2Date(dateString) {
3
const dt = dateString.split(/-|s/);
4
return new Date(dt.slice(0, 3).reverse().join('-') + ' ' + dt[3]);
5
}
6
7
// multiple formats (e.g. yyyy/mm/dd (ymd) or mm-dd-yyyy (mdy) etc.)
8
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {
9
const candidate = (dateStringCandidateValue || ``)
10
.split(/[ :-/]/g).map(Number).filter(v => !isNaN(v));
11
const toDate = () => {
12
format = [format].reduce((acc, val, i) => ({ acc, [val]: i }), {});
13
const parts =
14
[candidate[format.y], candidate[format.m] - 1, candidate[format.d] ]
15
.concat(candidate.length > 3 ? candidate.slice(3) : []);
16
const checkDate = d => d.getDate &&
17
![d.getFullYear(), d.getMonth(), d.getDate()]
18
.find( (v, i) => v !== parts[i] ) && d || undefined;
19
20
return checkDate( new Date(Date.UTC(parts)) );
21
};
22
23
return candidate.length < 3 ? undefined : toDate();
24
}
25
26
const result = document.querySelector('#result');
27
28
result.textContent =
29
`*FixedndateString2Date('01-01-2016 00:03:44'):n => ${
30
dateString2Date('01-01-2016 00:03:44')}`;
31
32
result.textContent +=
33
`nn*With formatting dmy
34
tryParseDateFromString('01-12-2016 00:03:44', 'dmy'):n => ${
35
tryParseDateFromString('01-12-2016 00:03:44', "dmy").toUTCString()}`;
36
37
result.textContent +=
38
`nn*With formatting mdy
39
tryParseDateFromString('03/01/1943', 'mdy'):n => ${
40
tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;
41
42
result.textContent +=
43
`nn*With invalid format
44
tryParseDateFromString('12-13-2016 00:03:44', 'dmy'):n => ${
45
tryParseDateFromString('12-13-2016 00:03:44', "dmy")}`;
46
47
48
result.textContent +=
49
`nn*With formatting invalid string
50
tryParseDateFromString('03/01/null', 'mdy'):n => ${
51
tryParseDateFromString('03/01/null', "mdy")}`;
52
53
result.textContent +=
54
`nn*With formatting no parameters
55
tryParseDateFromString():n => ${tryParseDateFromString()}`;
JavaScript
1
1
1
<pre id="result"></pre>