Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  192] [ 1]  / answers: 1 / hits: 128343  / 11 Years ago, tue, september 17, 2013, 12:00:00

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.


More From » jquery

 Answers
53

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]

[#75645] Monday, September 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
christianu

Total Points: 481
Total Questions: 124
Total Answers: 99

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
christianu questions
;