Pregunta

I've three different times, two of them are in string forms (time1 and time2) and one from system date currDate. Next step according to the one of two above times I want to print messages when the system date reaches one of them. For this I've function callEachMinute that calls each minute to get system time (but here in code I did not include the whole procedure). Here is the current status of the code:

Script:

function callEachMinute() {
    var currDate = new Date();
    var time_1 = '8:30';
    var time_2 = '23:00';

    timeComparison(currDate, time_1, time_2)
}

function timeComparison(currTime, time1, time2) {

    // Time 1 formatting
    var t1 = new Date();
    var parts1 = time1.split(":");
    t1.setHours(parts1[0],parts1[1]);

    // Iftor-Time formatting
    var t2 = new Date();
    var parts2 = timeI.split(":");
    t2.setHours(parts2[0],parts2[1]);

    /* Notification procedure */
    if (currTime == t1) {
        // Message for Time1
        alert("Time 1 is reached");
    }

    if (currTime == t2) {
        // Message for Time2
        alert("Time 2 is reached");
    }
}

Problem: When the system time is reached one of times (time1 or time2) nothing happens. Any solution for this problem?

¿Fue útil?

Solución

There are a few things that could be problematic here.

You set up a Date object then want to compare it to currTime:

if (currTime == t1) {

unfortunatley Javascript's == operator when applied to objects compares two objects to see if they are references to the same object, so even if currTime and t1 contained exactly the same time this check would evaluate to false since they are different instances. You could do this by converting to a string:

if (currTime.toString() == t1.toString) {

which would work if the string representations for each data work out the same.

However, a more straight forward approach might be to tackle this the other way around - extract the hours and minutes from currTime, build a string and compare that to your time strings. Something like:

// in timecomparison function
var hrs = currTime.getHours();
var mins = currTime.getMinutes();
var now = hrs+":"+mins

// now do comparisons
if (now == time1 ) {
    ....
}

and so on.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top