Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

jquery - Converting a datetime string to timestamp in Javascript

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...