Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

Converting between dates and timestamps in JavaScript

Posted: October 14, 2015
Written by: Saints At Play
Category: Javascript

Managing the conversion between dates and timestamps is relatively easy in JavaScript.

Converting a date to a timestamp

Using the parse method of the JavaScript Date object we can take a string date/time value and convert this into a unix timestamp like so:

Date.parse("13-Oct-2015 18:31:00")/1000

If we run the above code in our browser console we'd see a unix compliant timestamp like the following:

1444757460

Converting a timestamp to a date

If we take the above timestamp we can then convert this back into a date format using any of the following methods:

// With toDateString
new Date((1444757460 * 1000)).toDateString();

// With toLocaleString
new Date((1444757460 * 1000)).toLocaleString();

// With toGMTString
new Date((1444757460 * 1000)).toGMTString()

These different methods would output:

// With toDateString
"Tue Oct 13 2015"

// With toLocaleString
"13 October 2015 18:31:00 BST"

// With toGMTString
"Tue, 13 Oct 2015 17:31:00 GMT"

It's important to be aware that the above date functions may differ in how they are implemented on a browser-by-browser basis.

For maximum reliability across different platforms it would be wise to approach converting the timestamp to a human readable date format like so:

// Convert to timestamp
Date.parse("13-Oct-2015 18:31:00")

//Outputs: 1444757460000

// Generate the date ordinal indicator
// (Based on code shared at http://stackoverflow.com/a/6003589)
function generateOrdinal(numericDateValue) 
{
   switch (numericDateValue) 
   {
     case 1:
     case 21:
     case 31:
        return 'st';
     break;

     case 2:
     case 22:
        return 'nd';
     break;

     case 3:
     case 23:
        return 'rd';
     break;

     default:
        return 'th';
     break;
   }
}

// Take timestamp and format into human readable date
var d             =  new Date(1444757460000),
    days          =  ["Mon", 
                      "Tues", 
                      "Weds", 
                      "Thurs", 
                      "Fri", 
                      "Sat", 
                      "Sun"],
    months        =  ["January",
                      "February",
                      "March",
                      "April",
                      "May",
                      "June",
                      "July",
                      "August",
                      "September",
                      "October",
                      "November",
                      "December"],
    dayDigit      =  d.getDate(),
    dayOrdinal    =  generateOrdinal(dayDigit),
    day           =  days[d.getDay()],
    month         =  months[d.getMonth()],
    year          =  d.getFullYear(),
    hours         =  d.getHours(),
    minutes       =  d.getMinutes(),
    seconds       =  ("0" + d.getSeconds()).slice(-2); // Pad single digits with leading zero
console.log(day + ' ' + dayDigit + dayOrdinal + ' ' + month + ' ' + year + ' ' + hours + ':' + minutes + ':' + seconds); 

Run this in the browser console and you should see the following date returned:

Weds 13th October 2015 18:31:00

Yes, it's a lot more long-winded but, if you're concerned about platform consistency this would probably be the safest and most predictable route to go.

« Return to Posts

Comments

There are no comments

Posting comments after three months has been disabled.