JavaScript to Output Text Based on User's Current Time
Try following piece of Javascript code:
var today = new Date()
var curHr = today.getHours()
if (curHr < 12) {
console.log('good morning')
} else if (curHr < 18) {
console.log('good afternoon')
} else {
console.log('good evening')
}
var data = [
[0, 4, "Good night"],
[5, 11, "Good morning"], //Store messages in an array
[12, 17, "Good afternoon"],
[18, 24, "Good night"]
],
hr = new Date().getHours();
for(var i = 0; i < data.length; i++){
if(hr >= data[i][0] && hr <= data[i][1]){
console.log(data[i][2]);
}
}
Demo: http://jsfiddle.net/DerekL/we8Ty/
This is just a small variation of the solution from Derek 朕會功夫 above.
I felt the array is cleaner than a bunch of if
statements.
If you work the hours backwards, you don't need a start AND end hour.
Also, once you make a match, I added a break;
to kick out early.
var data = [
[22, 'Working late'],
[18, 'Good evening'],
[12, 'Good afternoon'],
[5, 'Good morning'],
[0, 'Whoa, early bird']
],
hr = new Date().getHours();
for (var i = 0; i < data.length; i++) {
if (hr >= data[i][0]) {
console.log(data[i][1])
break;
}
}