convert String to DateTime
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.
See also
// fixed format dd-mm-yyyy
function dateString2Date(dateString) {
const dt = dateString.split(/\-|\s/);
return new Date(dt.slice(0, 3).reverse().join('-') + ' ' + dt[3]);
}
// multiple formats (e.g. yyyy/mm/dd (ymd) or mm-dd-yyyy (mdy) etc.)
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {
const candidate = (dateStringCandidateValue || ``)
.split(/[ :\-\/]/g).map(Number).filter(v => !isNaN(v));
const toDate = () => {
format = [...format].reduce((acc, val, i) => ({ ...acc, [val]: i }), {});
const parts =
[candidate[format.y], candidate[format.m] - 1, candidate[format.d] ]
.concat(candidate.length > 3 ? candidate.slice(3) : []);
const checkDate = d => d.getDate &&
![d.getFullYear(), d.getMonth(), d.getDate()]
.find( (v, i) => v !== parts[i] ) && d || undefined;
return checkDate( new Date(Date.UTC(...parts)) );
};
return candidate.length < 3 ? undefined : toDate();
}
const result = document.querySelector('#result');
result.textContent =
`*Fixed\ndateString2Date('01-01-2016 00:03:44'):\n => ${
dateString2Date('01-01-2016 00:03:44')}`;
result.textContent +=
`\n\n*With formatting dmy
tryParseDateFromString('01-12-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('01-12-2016 00:03:44', "dmy").toUTCString()}`;
result.textContent +=
`\n\n*With formatting mdy
tryParseDateFromString('03/01/1943', 'mdy'):\n => ${
tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;
result.textContent +=
`\n\n*With invalid format
tryParseDateFromString('12-13-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('12-13-2016 00:03:44', "dmy")}`;
result.textContent +=
`\n\n*With formatting invalid string
tryParseDateFromString('03/01/null', 'mdy'):\n => ${
tryParseDateFromString('03/01/null', "mdy")}`;
result.textContent +=
`\n\n*With formatting no parameters
tryParseDateFromString():\n => ${tryParseDateFromString()}`;
<pre id="result"></pre>
Keep it simple with new Date(string)
. This should do it...
const s = '01-01-1970 00:03:44';
const d = new Date(s);
console.log(d); // ---> Thu Jan 01 1970 00:03:44 GMT-0500 (Eastern Standard Time)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
EDIT: "Code Different" left a valuable comment that MDN no longer recommends using Date as a constructor like this due to browser differences. While the code above works fine in Chrome (v87.0.x) and Edge (v87.0.x), it gives an "Invalid Date" error in Firefox (v84.0.2).
One way to work around this is to make sure your string is in the more universal format of YYYY-MM-DD (obligatory xkcd), e.g., const s = '1970-01-01 00:03:44';
, which seems to work in the three major browsers, but this doesn't exactly answer the original question.