I am attempting to use a JavaScript alert greeting based on the user’s local time, but it doesn’t seem to work. The script worked fine until I added the timezone offset. Now it doesn’t alert at all. Here is the script:
function greeting() {
var x = new Date().getHours();
var y = x.getTimezoneOffset();
if (y >= 5 && y < 11) {
alert("Good morning!");
} else if (y >= 11 && y < 17) {
alert("Good afternoon!");
} else if (y >= 17 && y < 21) {
alert("Good evening!");
} else {
alert("Good night!");
}
}
I’m new to JavaScript and would appreciate any help you can give me. Thank you.
getTimezoneOffset Returns the time difference between UTC time and local time, in minutes therefore it will return the same value regardless of what time of day it is. It could also be a negative value. The Offset in the method identifier is the clue.
My script is an hour ahead. For instance, at 11:30 A.M. it will alert “Good Afternoon!” when that shouldn’t happen until noon. I know the hours start at 0 and run to 23 which I allowed for here. I don’t know why this is happening if the local time zone is automatic. I understand now that an offset isn’t the right way, but how do I fix this?
First step is to put in an alert for the value returned by the getHours method. If it is returning anything other than 10 at 11:30am. the problem isn’t in your code.