Reputation: 1003
I have a Razor form that has the following fields:
Startdate
Starttime (24 hr)
EndDate
EndTime (24hr)
BreakDuration (increments of 15 minutes)
StartDate and Start Time an EndDate and EndTime eventually end up combined into one SQL DateTime Field..
I need a field in the form that displays the duration - so basically the days, hours, minutes between the start and end, minus the break duration.
for example: Total Time:36:15 hrs
It would also be really useful if the End Date could be auto-incremented when the start time and end time seem to span over a day.. eg start-time 10pm -> end-time 7am.
But anyway here is my jsfiddle using moment.js
http://jsfiddle.net/beebul/kwdo9yrj/
HTML:
<div class="conthttp://jsfiddle.net/beebul/kwdo9yrj/49/#forkrols">
<input type="text" style="width:300px" name="momentDurationHours" id="momentDurationHours" readonly="" />
<a href="#" id="show">Show Total duration</a>
</div>
JavaScript:
$('#show').click(function () {
{
var startDate = '28/10/2010'; //taken from the date and time pickers
var endDate = '29/10/2010';
var startTime = '12:00';
var endTime = '17:00';
var breakduration = '01:25:00';
var joinStartDates = startDate + " " + startTime;
var joinEndDates = endDate + " " + endTime;
var totalHours = moment(joinEndDates, "DD/MM/YYYY HH:mm").diff(moment(joinStartDates, "DD/MM/YYYY HH:mm"), 'minutes');
var breaktime = moment.duration(breakduration, 'HH:mm').asMinutes();
var takeBreak = totalHours - breaktime;
//this bit below doesn't work but you get the idea...
//var totalHoursMinusBreak = moment(takeBreak).format("HH:mm"); //trying to convert mins to HH:mm
$('input[name="momentDurationHours"]').val(totalHours + " min - break: " + breaktime + "mins = TOTAL AS HRS?? ");
}
});
I got tied in knots trying to use the moment.js subtract function so decided to convert to minutes first and then try and convert the final minutes total to HH:mm
Many thanks for any tips and suggestions.
Upvotes: 2
Views: 3118
Reputation: 10466
Try something like this using moment.js
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
// outputs: "48:39:30"
Upvotes: 2