Calculate time between two dates


Using moment.js, We can calculate time between two dates in jquery.
JavaScript

//Dates in string format
var strStartDate = "07/29/2017"; //MM/DD/YYYY
var strEndDate = "08/30/2017"; //MM/DD/YYYY

//Times in string format
var strStartTime="12:25";  //HH:MM
var strEndTime="22:30";  //HH:MM

//Convert string dates to Date format and adding time to dates
var StartDateTime = (moment(strStartDate,"MM/DD/YYYY").add(strStartTime.split(':')[0],'hours')).add(strStartTime.split(':')[1],'minutes');

var EndDateTime =(moment(strEndDate,"MM/DD/YYYY").add(strEndTime.split(':')[0],'hours')).add(strEndTime.split(':')[1],'minutes');

//Calculate duration
var duration = moment.duration(EndDateTime.diff(StartDateTime));

//Convert duration in hours
var hours = duration.asHours();
//Convert duration in minutes
var minutes = duration.asMinutes();

//Display on screen
$("#StartDate").html(StartDateTime.format("MMM DD, YYYY, HH:mm:ss"));
$("#EndDate").html(EndDateTime.format("MMM DD, YYYY, HH:mm:ss"));
$("#Hours").html(hours);
$("#Minutes").html(minutes);


Html

<h2>Calculate time between two dates</h2>
Start Date Time : <div id="StartDate"></div>
End Date Time : <div id="EndDate"></div>
Hours : <div id="Hours"></div>
Minutes : <div id="Minutes"></div>


Result
Calculate time between two dates
Start Date Time :
Jul 29, 2017, 12:25:00
End Date Time :
Aug 30, 2017, 22:30:00
Hours :
778.0833333333334
Minutes :
46685
Try it

Leave a Reply

Your email address will not be published. Required fields are marked *