Javascript Time Functions
by Alexis Hope,
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 a parameter and 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 for converting other values to human-friendly names. While it won’t cover all edge cases it services the majority.
{% highlight javascript %} /*
- 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; } {% endhighlight %}
Tags: