27

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.

12
  • 3
    What's wrong with Date.parse(), how does it not work? Commented Sep 17, 2013 at 12:12
  • 1
    You can use moment.js: momentjs.com to convert time to milliseconds Commented Sep 17, 2013 at 12:13
  • What exactly do you mean convert to milliseconds? You can't just convert a date to milliseconds. A date is a reference to a specific point in time, milliseconds are a measurement of time from a specific point, if you see my meaning. You can get the number of milliseconds from a specific date, like the number of millis since 17-9-2013, but since you have an entire column of dates, I'm guessing this isn't what you want. Or you can add millis to the current time to get a more exact point, is this what you're looking for? Commented Sep 17, 2013 at 12:14
  • 1
    @Pekka error : TypeError: Date.parse is not a constructor Commented Sep 17, 2013 at 12:14
  • Look at the console when coding. Look at the documentation for Date.parse(). Is your date string in a valid format? The docs will tell you. Commented Sep 17, 2013 at 12:15

5 Answers 5

41

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"]
Sign up to request clarification or add additional context in comments.

4 Comments

what can I do with dateParts ?
@JanithChinthana Well, the regular expression example just shows an alternative way of parsing the date string instead of using multiple split calls.
Link to MDN (not W3)! Nice. +1
@plalx, it is not working when var dateString = '17-09-2013 10:08:30'; basically not working when there is second counterpart
19

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);

3 Comments

Date.parse() is the best solution. It works in every situation.
Not true. I have an example with NaN
So what is your example ? @GrávujMiklósHenrich
8

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

9 Comments

Just as clarification: date-month-year hour(24):minute will be parsed as month-date-year hour(24):minute; that's what this fixes.
@ Sumurai8: OP's question is what's the easiest way to convert the time into ms. What's the other part?
I try this and it getting undefined in s.split('-')
@kadaj He came here in the first place because there was an error in his code. I suppose you are right though. I believe new Date(...).getTime() and Date.parse(...) do the same thing.
@Janith Chinthana What does s print?
|
1

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');

Comments

1

It is just as simple:

   var today = new Date(); // Thu Apr 28 2022 21:51:23 GMT+0530
   var todaysTimestamp = new Date().getTime();   // 1651162883379

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.