2

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

Kunle
  • 58
  • 2
  • 9
  • what is ```valuestop``` in your code – Atul Mathew Nov 30 '19 at 11:09
  • 1
    getMinutes returns the minutes in the current hour, this is probably not what you want: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes I would suggest using .getTime() to calculate the time difference in milliseconds and calculate the days/hours/minutes from there – vnglst Nov 30 '19 at 11:12
  • 1
    `var differenceInMilliseconds = (new Date()) - (new Date("01/01/2017 " + valuestop))` – Andreas Nov 30 '19 at 11:19

1 Answers1

0

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);
arici
  • 77
  • 8