Question in brief:
What is the easiest way to convert date-month-year hour(24):minute to timestamp?
due to more views add clear question on the top, so that no need to go through background & all if need quick help.
Background :
I have a simple html table and I used jquery sorter to sort my table columns.
Everything is working fine except a date column which is having following format of data,
17-09-2013 10:08 date-month-year hour(24):minute
This column is sorting(alphabetically) but not as I expected(date wise). I tried to use a custom parser as follows,
$.tablesorter.addParser({
id: 'date_column', // my column ID
is: function(s) {
return false;
},
format: function(s) {
var timeInMillis = new Date.parse(s);
return timeInMillis;
},
type: 'numeric'
});
Problem :
it fails due to new Date.parse(s) .
Question :
what is the easiest way to convert date-month-year hour(24):minute to timestamp? then I can skip var timeInMillis = new Date.parse(s); line.
Thanks
Edited :
Sorry about the confusion about milliseconds, actually it should be the timestamp which is a number that represents the current time and date.
Advertisement
Answer
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"]