Displaying Hours and Minutes as Words in JS

3.9k views Asked by At

BACKGROUND: I'm using getHours() and getMinutes() to display the time on a page.

PROBLEM: I'm trying to figure out how to convert the numerical time (i.e., "21:00") to a written-out hour and minutes format (i.e. "nine 0'clock").

My JS:

function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
// add a zero in front of numbers<10
  m=checkTime(m);
  document.getElementById('time').innerHTML="The time is "+h+" o'clock and "+m+" past";
t=setTimeout(function(){startTime()},500);
}

  function checkTime(i)
  {
  if (i<10)
    {
    i="0" + i;
    }
  return i;
  } 

Here's a fiddle

1

There are 1 answers

2
jfriend00 On BEST ANSWER

You can use a lookup table or an array to convert numbers to names.

function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    // add a zero in front of numbers greater than 10
    document.getElementById('time').innerHTML = "The time is " + convertHourToName(h) + " o'clock and " + convertNumberToName(m) + " past";
    setTimeout(startTime,500);
}

function checkTime(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
} 

function convertHourToName(num) {
    if (num > 12) {
        num -= 12;
    }
    return convertNumberToName(num);
}

function convertNumberToName(num) {
    var lowNames = ["zero", "one", "two", "three", 
                  "four", "five", "six", "seven", "eight", "nine", 
                 "ten", "eleven", "twelve", "thirteen", "fourteen", 
                  "fifteen", "sixteen", "seventeen", 
                  "eighteen", "nineteen"];
    var tensNames = ["twenty", "thirty", "forty", "fifty", 
                "sixty", "seventy", "eighty", "ninety"];
    var tens, ones, result;
    if (num < lowNames.length) {
        result = lowNames[num];
    } else {
        tens = Math.floor(num / 10);
        ones = num % 10;
        if (tens <= 9) {
            result = tensNames[tens - 2];
            if (ones > 0) {
                result += " " + lowNames[ones];
            }
        } else {
            result = "unknown"
        }
    }
    return result;
}

startTime();

Working demo: http://jsfiddle.net/jfriend00/EmALf/