Javascript Time Functions

by Alexis Hope, 26 Nov 2010

A quick note on converting javascript time stamps to human readable format. I had been working on a travel calculator with new google maps v3 which required this for UI.

The following function takes a javascript Date object as parameter converts it to a human readable string.

The functions themselves are simplistic. But can be tedious to work out in a pinch. Also the pluralise function is a good starting point to convert other values to human friendly names. While it wont cover all edge cases it service the majority.

 * format time from Date to string
 * @param time:Date
 * return string
function timeNice(time) {
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var nicetime = hours + ' ' + pluralize(hours, 'hour', 's') + ' ' 
          + minutes + ' ' + pluralize(minutes, 'minute', 's');
    return nicetime;

function pluralize (count, word, suffix) {
  return count === 1 ? word : word + suffix;