Reputation: 21
Hope to get some help with this. I am total novice to JS. I have to write a script that asks user for the current hour. That's easy. If the hour is between 6am and 9 am, it will give certain prompt. If the hour is between 11 am and 1 pm, another prompt. If between 5 pm and 8 pm, prompt. My issue is how to have JS understand when user enters let's say number 5, that it is 5 pm (time for dinner) and not 5 am (go get snack). Please, help me. What would be solution to my problem? No one in the US really uses 24 hour format so numbers 13 (1pm), 17(5pm) or 20(8pm) in my script wont work. I can only have inputs in 12 hour time format.
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.");
}
Upvotes: 2
Views: 368
Reputation: 242
Well make a parser to parse 12 > 24 hour You could do this:
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)
}
That is all I worked out and the output is a int.
So leave the code alone.
Output is in 24 hour.
Upvotes: 1
Reputation: 19791
I would use JavaScript's String.match() to compare the string to a RegExp that describes the hour format such as /^(\d{1,2})\s*(am|pm)?$/i
. This RegExp means:
^
match the start of the string(\d{1,2})
match and capture 1 or 2 digits (ie, 0-9) \s*
match 0 or more whitespace characters(am|pm)?
optionally match and capture 'am'
or 'pm'
$
match the end of the stringi
at the end means ignore the upper/lowercasing for the matches (ie match 'am'
or 'AM'
)Also, I'd throw a loop around the prompt in case the user didn't enter the correct format.
Here's a complete sample.
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
Upvotes: 1