Converting a datetime string to timestamp in Javascript
Seems like the problem is with the date format.
var d = "17-09-2013 10:08",
dArr = d.split('-'),
ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000
Date.parse()
isn't a constructor, its a static method.
So, just use
var timeInMillis = Date.parse(s);
instead of
var timeInMillis = new Date.parse(s);
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond])
constructor signature of the Date
object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400
You could also use a regular expression with capturing groups to parse the date string in one line.
var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);
console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]
For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:
function convertDate(date) {
// # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
var dateTimeParts = date.split(' ');
// # this assumes time format has NO SPACE between time and am/pm marks.
if (dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {
var theTime = dateTimeParts[1];
// # strip out all except numbers and colon
var ampm = theTime.replace(/[0-9:]/g, '');
// # strip out all except letters (for AM/PM)
var time = theTime.replace(/[[^a-zA-Z]/g, '');
if (ampm == 'pm') {
time = time.split(':');
// # if time is 12:00, don't add 12
if (time[0] == 12) {
time = parseInt(time[0]) + ':' + time[1] + ':00';
} else {
time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
}
} else { // if AM
time = time.split(':');
// # if AM is less than 10 o'clock, add leading zero
if (time[0] < 10) {
time = '0' + time[0] + ':' + time[1] + ':00';
} else {
time = time[0] + ':' + time[1] + ':00';
}
}
}
// # create a new date object from only the date part
var dateObj = new Date(dateTimeParts[0]);
// # add leading zero to date of the month if less than 10
var dayOfMonth = (dateObj.getDate() < 10 ? ("0" + dateObj.getDate()) : dateObj.getDate());
// # parse each date object part and put all parts together
var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;
// # finally combine re-formatted date and re-formatted time!
var date = new Date(yearMoDay + 'T' + time);
return date;
}
Usage:
date = convertDate('11/15/2016 2:00pm');