Search code examples
javascriptdatetimedate-formatting

Calculate the day difference between two time


I have two date format and I need to calculate the hour difference between both.

First date is current date. Second Date is in below format :

var depDate = 25092018  //ddmmyyyy
var depTime = 08:35 //hh:mm

new Date function doesn't take date in format ddmmyyyy. How can input depDate in new Date function

I want to check the difference between current date and depDate.

Can anybody help ?


Solution

  • Your date in variable depDate hasn't valid format. You need to validate format of it using regex in .replace(). Then use Date.prototype.getTime() getting numeric value of date.

    var depDate = "25092018";  
    var depTime = "08:35";
    var dateStr = depDate.replace(/(\d{2})(\d{2})(\d{4})/, "$3-$2-$1")+"T"+depTime;
    // dateStr => 2018-09-25T08:35
    
    var timeDiff = Math.abs(new Date(dateStr).getTime() - new Date().getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
    // 1000 => to converting millisecond to second
    // 3600 => to converting second to hour
    // 24 =>   to converting hour to day                    
    console.log(diffDays);