Reputation: 133
So, I'm making a program, where when a specific function is called, it checks the current time, and executes an action depending on the time. Currently, inside my function, here is my code:
var d = new Date();
var currentTime = d.toLocaleTimeString();
var timeSplit = currentTime.split(':');
var timeH = timeSplit[0];
var timeM = timeSplit[1];
var timePM = timeSplit[2].split(' ')[1]
if (timeH >= 9 && timeM >= 30 && timePM == 'AM') {
function1()
} else if (timeH == 10 && timeM >= 25 && timeM < 30 && timePM == 'AM') {
function2()
} else if (timeH >= 10 && timeM <= 30 && timePM == 'AM') {
function3()
} else if (timeH >= 11 && timeM >= 40 && timePM == 'AM') {
function4()
}
You kinda get the point
It doesn't return any errors, but it also doesn't execute any functions either. How can I fix this?
Upvotes: 0
Views: 879
Reputation: 201553
I think that in your script, timePM
might be undefined
. By this, no functions in the if statement are not run.
So how about this modification?
var currentTime = d.toLocaleTimeString();
var currentTime = d.toLocaleTimeString('en-US');
var currentTime = d.toLocaleTimeString();
var timeSplit = currentTime.split(':');
var timeH = timeSplit[0];
var timeM = timeSplit[1];
var timePM = timeSplit[2].split(' ')[1]
var h = d.getHours();
var timeH = h < 12 ? h : h - 12;
var timeM = d.getMinutes();
var timePM = d.getHours() < 12 ? 'AM' : 'PM';
Upvotes: 2