Search code examples
javascriptjquerytimer

How do i subtract End Time from Start Time without having negative minutes in Javascript timer


I need to subtract end time from start time to create a count down timer, I also want to avoid getting negative minutes. how do I do this.

var timeStart = new Date().getHours();
var timeEnd = new Date("01/01/2007 " + valuestop).getHours();
var timeStartMin = new Date().getMinutes();
var timeEndMin = new Date("01/01/2007 " + valuestop).getMinutes();

var difference = timeEnd - timeStart;
var differenceMin = timeEndMin - timeStartMin;

the timer works fine, but VAR differenceMin is negative


Solution

  • I did not understand why you are getting differences between start and end because mostly for countdowns we use end-time and now difference. But anyway I am sending what you want and if you want you can use this function to get a difference between end and now too.

    var getTimeDifference=function(from,to){
        var difMs = (from - to);
        if(difMs<=0){
            return 0 + " days, " + 0 + " hours, " + 0 + " mins";
        }else{
            var difDays = Math.floor(difMs / 86400000);
            var difHrs = Math.floor((difMs % 86400000) / 3600000);
            var difMins = Math.round(((difMs % 86400000) % 3600000) / 60000);
            return diffDays + " days, " + difHrs + " hours, " + diffMins + " mins";
        } 
    }
    var startTime= new Date('12-30-2019 20:00:00');
    var endTime= new Date('11-1-2019 16:00:00');
    getTimeDifference(endTime,startTime);