javascript - Moment.js format difference - Stack Overflow

In one of my projects i have to calculate the difference between two times. For example the work hours

In one of my projects i have to calculate the difference between two times. For example the work hours starts at 6:30 and finishes at 10 o'clock. The difference is 3 hours and 30 minutes. I write a small JS function to handles the task and it works great, gives me the following result: 3.5. I tried .format("HH:mm") but the result was undefined not a function.
Is there any method that converts the output like "HH:mm"?

Here is the dateDiff function:

function dateDiff() {
    var startTime = moment(document.getElementById("startTime").value, "HH:mm");
    var endTime = moment(document.getElementById("end").value, "HH:mm");

    var duration = moment.duration(endTime.diff(startTime));
    var hours = duration.asHours();
    console.log(hours);
    document.getElementById('dateDiffResult').value = moment(hours);
}

In one of my projects i have to calculate the difference between two times. For example the work hours starts at 6:30 and finishes at 10 o'clock. The difference is 3 hours and 30 minutes. I write a small JS function to handles the task and it works great, gives me the following result: 3.5. I tried .format("HH:mm") but the result was undefined not a function.
Is there any method that converts the output like "HH:mm"?

Here is the dateDiff function:

function dateDiff() {
    var startTime = moment(document.getElementById("startTime").value, "HH:mm");
    var endTime = moment(document.getElementById("end").value, "HH:mm");

    var duration = moment.duration(endTime.diff(startTime));
    var hours = duration.asHours();
    console.log(hours);
    document.getElementById('dateDiffResult').value = moment(hours);
}
Share Improve this question asked Apr 19, 2016 at 10:38 GabeszGabesz 3034 silver badges14 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You could just get the hours and minutes separately and format the string:

function dateDiff() {
    var startTime = moment(document.getElementById("startTime").value, "HH:mm");
    var endTime = moment(document.getElementById("end").value, "HH:mm");

    var duration = moment.duration(endTime.diff(startTime));
    var hours = duration.hours();
    var minutes = duration.minutes();
    document.getElementById('dateDiffResult').value = hours +":"+ minutes;
}

if your function works and gives you the time difference in hours, surely it is then simple to calculate the hours and minutes from the number of hours? Using your stated difference of 3.5...

var diff=3.5;
var hour=Math.floor(diff);//gives  hour=3;
var hours=("0"+ hour).slice(-2);//pads the hours with a leading zero if required to give hours=03;

var minute = (diff-hour)*60;//gives 30
var minutes=("0"+ minute ).slice(-2);//pads the minutes with a leading zero if required to give minutes=30;
var totalDiff= hours + ":" +minutes; //gives 03:30 as in HH:MM

I added the following to demonstrate this in the snippet:

$(document).ready
	(function(){

		var diff=3.5;
var hour=Math.floor(diff);//gives  hour=3;
var hours=("0"+ hour).slice(-2);//gives  hours=03;

var minute = (diff-hour)*60;//gives 30
var minutes=("0"+ minute ).slice(-2);//gives  minutes=30;
var totalDiff= hours + ":" +minutes; //gives 03:30 as in HH:MM
alert("HH:MM: " + totalDiff);
	})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Using a time-field jQuery plugin, you can generate time fields. After that, you can listen to changes to the fields and update the hours difference accordingly.

(function($) {
  $.initTimeFields = function(interval) {
    $('.time-field').each(function(_, field) {
      $(field).initTimeField(interval);
    });
  };
  $.fn.initTimeField = function(interval) {
    var hour = 0, minute = 0, diff;
    while (hour < 24 && minute < 60) {
      this.append($('<option>', {
        val : hour * 60 + minute,
        text : ('00' + hour).substr(-2) + ':' + ('00' + minute).substr(-2)
      }));
      minute += interval;
      diff = minute - 60;
      if (diff >= 0) {
        hour += 1;
        minute %= 60;
      }
    }
    var value = this.data('value') || 0;
    if (typeof value === 'string' && value.indexOf(':') > -1) {
      value = (function(values) {
        return parseInt(values[0], 10) * 60 + parseInt(values[1], 10);
      }(value.split(':')));
    }
    this.val(value);
  };
}(jQuery));

function updateTimeDiff() {
  $('#hour-diff').val(calcHourDiff(getTime('#start-time'), getTime('#end-time')) + ' hours');
}
function calcHourDiff(startTime, endTime) {
  var diff = moment.duration(endTime.diff(startTime));
  return ('00' + diff.hours()).substr(-2) + ':' + ('00' + diff.minutes()).substr(-2);
}
function getTime(selector) {
  return moment($(selector).find('option:selected').text(), "HH:mm");
}

$('.time-field').on('change', function() {
  updateTimeDiff()
});

// Main
$.initTimeFields(15);
$('.time-field').trigger('change');
label { display: inline-block; width: 3em; }
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.13.0/moment.min.js"></script>

<label>Start: </label><select id="start-time" class="time-field" data-value="06:30"></select><br />
<label>End:   </label><select id="end-time"   class="time-field" data-value="10:00"></select><br />
<label>Diff:  </label><input  id="hour-diff"  type="text"  size="8" />

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745357615a4624211.html

相关推荐

  • javascript - Moment.js format difference - Stack Overflow

    In one of my projects i have to calculate the difference between two times. For example the work hours

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信