如何使JS解析12小时输入格式为24或

时间:2013-10-11 04:45:56

标签: javascript

希望能得到一些帮助。我是JS的新手。我必须写一个脚本,询问用户当前的小时。这很简单。如果时间是早上6点到早上9点,它会给出一定的提示。如果小时是在上午11点到下午1点之间,则另一个提示。如果在下午5点到晚上8点之间,提示。我的问题是如何让JS了解当用户输入让我们说5号,即下午5点(晚餐时间)而不是5点(去吃零食)。请帮我。什么可以解决我的问题?美国没有人真正使用24小时格式,因此我的剧本中的13(下午1点),17(下午5点)或20(晚上8点)的数字不会起作用。我只能以12小时的时间格式输入。

var hour=prompt("What is the current hour? ","");

  if( hour >= 6 && hour <= 9 ){
    alert("Breakfast is served.");
  }
  else if( hour >=11  && hour <= 13 ){
    alert("Time for lunch.");
  }
  else if( hour >=17  && hour <= 20 ){
    alert("It's dinner time.");
  }
  else {
    alert("Sorry, you'll have to wait, or go get snack.");
  }

2 个答案:

答案 0 :(得分:1)

我会使用JavaScript's String.match()将字符串与描述小时格式的RegExp进行比较,例如/^(\d{1,2})\s*(am|pm)?$/i。这个RegExp意味着:

  • ^匹配字符串的开头
  • (\d{1,2})匹配并捕获1或2位数字(即0-9)
  • \s*匹配0个或更多空格字符
  • (am|pm)?可选地匹配并捕获'am''pm'
  • $匹配字符串的结尾
  • 最后
  • i表示忽略匹配的大写/小写(即匹配'am''AM'

另外,如果用户没有输入正确的格式,我会在提示符周围抛出一个循环。

这是一个完整的样本。

var hour;
var done = false;

while (!done) {
  var answer = prompt("What is the current hour?","");
  var result = answer.match(/^(\d+)\s*(am|pm)?$/i);
  if (result) {
    hour = +result[1];
    if (result[2] && result[2].match(/pm/)) {
      // If pm was specified, add 12
      hour += 12;
    }
    if (hour < 24) {
      done = true;
    }
  }
}

... Your code as before

答案 1 :(得分:1)

好好使解析器解析12&gt; 24小时 你可以这样做:

var hour   = prompt("What is the current hour? ","");
var apm    = hour.replace(/[0-9]/g, '');
var thour  = ""
if(apm = "am"){
  thour = parseInt(hour);
  out(thour);
}
else{
  thour = parseInt(hour) + 12;
  out(thour);
}
out = function(hour) {
(Your Code Here)
}

这就是我解决的问题,输出是一个int。 所以请保持代码单独 输出时间为24小时。