How to convert string like '01-01-1970 00:03:44'
to datetime?
-
possible duplicate of http://stackoverflow.com/questions/476105/how-can-i-convert-string-to-datetime-with-format-specification-in-javascript – S L Apr 01 '11 at 08:01
-
Your question seems to be a duplicate of this one: http://stackoverflow.com/q/476105/684934 – Apr 01 '11 at 08:03
-
Please check this; http://stackoverflow.com/a/25961926/1766100 It worked for me. – Fatih Çelik Jan 26 '16 at 12:47
12 Answers
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.

- 18,811
- 16
- 99
- 115
-
10Why is this not the chosen answer? This is probably the most intuitive answer here. – hlin117 Jun 24 '15 at 21:39
-
1Not on safari. Doing this with this string format results in an invalid date – yeahdixon Aug 10 '16 at 17:26
-
More information on safari issues: http://stackoverflow.com/questions/4310953/invalid-date-in-safari When possible I would suggest you use the date string format that is quoted in the accepted answer. Hopefully Safari will eventually conform to the standard. In the meantime, an additional library may be needed if this is a problem for you. – Luke Aug 12 '16 at 17:57
-
2DO NOT USE THIS METHOD. The datetime format is browser-specific. From [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date): "Note: Parsing of date strings with the `Date` constructor (and `Date.parse()`, which works the same way) is strongly discouraged due to browser differences and inconsistencies." – Code Different Jan 17 '21 at 16:01
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.
// 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>

- 119,216
- 31
- 141
- 177
You could use the moment.js library.
Then simply:
var stringDate = '01-01-1970 00:03:44';
var momentDateObj = moment(stringDate);
Checkout their api also, helps with formatting, adding, subtracting (days, months, years, other moment objects).
I hope this helps.
Rhys

- 1,699
- 13
- 24
-
1how do you know that your stringDate is structured as dd-mm and not mm-dd with your answer? what if the local settings of a chinese browser is refering to 01-01-1970 as mm-dd-yyyy and another browser is in another location is dd-mm-yyyy? – themhz Apr 28 '17 at 16:32
-
http://www.w3schools.com/jsref/jsref_parse.asp
<script type="text/javascript">
var d = Date.parse("Jul 8, 2005");
document.write(d);<br>
</script>

- 3,670
- 1
- 23
- 21

- 2,068
- 2
- 18
- 31
well, thought I should mention a solution I came across through some trying. Discovered whilst fixing a defect of someone comparing dates as strings.
new Date(Date.parse('01-01-1970 01:03:44'))

- 406
- 7
- 13
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
var unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');
console.log(unixTimeZero);
// expected output: 0
console.log(javaScriptRelease);
// expected output: 818035920000

- 5,353
- 1
- 38
- 35
formatDateTime(sDate,FormatType) {
var lDate = new Date(sDate)
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var hh = lDate.getHours() < 10 ? '0' +
lDate.getHours() : lDate.getHours();
var mi = lDate.getMinutes() < 10 ? '0' +
lDate.getMinutes() : lDate.getMinutes();
var ss = lDate.getSeconds() < 10 ? '0' +
lDate.getSeconds() : lDate.getSeconds();
var d = lDate.getDate();
var dd = d < 10 ? '0' + d : d;
var yyyy = lDate.getFullYear();
var mon = eval(lDate.getMonth()+1);
var mm = (mon<10?'0'+mon:mon);
var monthName=month[lDate.getMonth()];
var weekdayName=weekday[lDate.getDay()];
if(FormatType==1) {
return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi;
} else if(FormatType==2) {
return weekdayName+', '+monthName+' '+
dd +', ' + yyyy;
} else if(FormatType==3) {
return mm+'/'+dd+'/'+yyyy;
} else if(FormatType==4) {
var dd1 = lDate.getDate();
return dd1+'-'+Left(monthName,3)+'-'+yyyy;
} else if(FormatType==5) {
return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi+':'+ss;
} else if(FormatType == 6) {
return mon + '/' + d + '/' + yyyy + ' ' +
hh + ':' + mi + ':' + ss;
} else if(FormatType == 7) {
return dd + '-' + monthName.substring(0,3) +
'-' + yyyy + ' ' + hh + ':' + mi + ':' + ss;
}
}

- 21
- 1
For this format (supposed datepart has the format dd-mm-yyyy) in plain javascript:
var dt = '01-01-1970 00:03:44'.split(/\-|\s/)
dat = new Date(dt.slice(0,3).reverse().join('/')+' '+dt[3]);

- 2,948
- 2
- 22
- 41
By using Date.parse()
you get the unix timestamp.
date = new Date( Date.parse("05/01/2020") )
//Fri May 01 2020 00:00:00 GMT

- 1,917
- 17
- 28
var dt = '01-02-2021 12:22:55'.split(/\-|\s/)
dat = new Date(dt.slice(0,3).reverse().join('/')+' '+dt[3]);
console.log(dat.toLocaleDateString())

- 899
- 2
- 9
- 18

- 21
- 2
-
2Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. – 0xLogN Apr 06 '21 at 00:53
I found a simple way to convert you string to date.
Sometimes is not correct to convert this way
let date: string = '2022-05-03';
let convertedDate = new Date(date);
This way is not ok due to lack of accuracy, sometimes the day is changed from the original date due to the date's format.
A way I do it and the date is correct is sending the date parameters
let date: string = '2022-05-03';
let d: string = date.split('-');
let convertedDate = new Date(+d[0], +d[1] - 1, +d[2]); //(year:number, month:number, date:number, ...)
console.log(date);
console.log(convertedDate);
This is the Output:
Output
2022-05-03
Tue May 03 2022 00:00:00 GMT-0400 (Atlantic Standard Time)
The date can accept a lot more parameters as hour, minutes, seconds, etc.

- 374
- 2
- 9
After so much reasearch I got my solution using Moment.js:
var date = moment('01-01-1970 00:03:44', "YYYY-MM-DD").utcOffset('+05:30').format('YYYY-MM-DD HH:mm:ss');
var newDate = new Date(moment(date).add({ hours:5, minutes: 30 }).format('YYYY-MM-DD hh:mm:ss'));
console.log(newDate)
//01-01-1970 00:03:44

- 5,031
- 17
- 33
- 41

- 1
- 1