1

背景:我正在使用getHours()andgetMinutes()在页面上显示时间。

问题:我试图弄清楚如何将数字时间(即“21:00”)转换为写出的小时和分钟格式(即“九点钟”)。

我的 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;
  } 

这是一个小提琴

4

1 回答 1

1

您可以使用查找表或数组将数字转换为名称。

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();

工作演示:http: //jsfiddle.net/jfriend00/EmALf/

于 2013-09-14T01:33:00.677 回答