Reputation: 56179
How to convert string like '01-01-1970 00:03:44'
to datetime?
Upvotes: 73
Views: 350708
Reputation: 21
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())
Upvotes: 1
Reputation: 11
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
Upvotes: 0
Reputation: 122888
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>
Upvotes: 20
Reputation: 382
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.
Upvotes: 0
Reputation: 19941
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.
Upvotes: 135
Reputation: 2267
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
Upvotes: 1
Reputation: 426
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'))
Upvotes: 4
Reputation: 2158
http://www.w3schools.com/jsref/jsref_parse.asp
<script type="text/javascript">
var d = Date.parse("Jul 8, 2005");
document.write(d);<br>
</script>
Upvotes: 9
Reputation: 5773
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
Upvotes: 3
Reputation: 3177
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]);
Upvotes: 1
Reputation: 1707
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
Upvotes: 8
Reputation: 21
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;
}
}
Upvotes: 2