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.

Janith Chinthana
  • 3,792
  • 2
  • 27
  • 54
  • 3
    What's wrong with `Date.parse()`, how does it not work? – Pekka Sep 17 '13 at 12:12
  • 1
    You can use `moment.js`: http://momentjs.com/ to convert time to milliseconds – Biketire Sep 17 '13 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? – BeanBagKing Sep 17 '13 at 12:14
  • 1
    @Pekka error : `TypeError: Date.parse is not a constructor` – Janith Chinthana Sep 17 '13 at 12:14
  • Look at the console when coding. Look at the documentation for [`Date.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse). Is your date string in a valid format? The docs will tell you. – epascarello Sep 17 '13 at 12:15
  • @BeanBagKing I need something like timestamp – Janith Chinthana Sep 17 '13 at 12:16
  • @JanithChinthana http://stackoverflow.com/questions/8123878/data-parse-is-not-a-constructor – Sumurai8 Sep 17 '13 at 12:16
  • Just a suggestion: Unless your format is a requirement, I might suggest formatting as [yyyy-mm-dd hh:mm:ss] as it's easily sortable without conversion. – Duncan Sep 17 '13 at 12:17
  • @epascarello my format is not in that list – Janith Chinthana Sep 17 '13 at 12:17
  • @epascarello The problem is that he is using the new keyword. – Sumurai8 Sep 17 '13 at 12:18
  • @Sumurai8 even I remove that, it is not working – Janith Chinthana Sep 17 '13 at 12:21
  • @Sumurai8 hence my first part of my comment to look at the console and that is half the problem. The other problem is the a valid string does not represent a RFC2822 or ISO 8601 date. – epascarello Sep 17 '13 at 12:25

5 Answers5

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"]
ObiHill
  • 11,448
  • 20
  • 86
  • 135
plalx
  • 42,889
  • 6
  • 74
  • 90
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);
Rémi Becheras
  • 14,902
  • 14
  • 51
  • 81
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
4b0
  • 21,981
  • 30
  • 95
  • 142
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');
Community
  • 1
  • 1
recurse
  • 624
  • 6
  • 15
0

It is just as simple:

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