Get total hours with exact minutes

时间:2018-02-03 10:11:32

标签: javascript jquery

Please help me out how to get minutes.

Example:

var time_in = '09:15';
var break_out = '12:00';
var break_in = '13:00';
var time_out = '18:00';
var date = '2018-01-31';

var morning = (
  new Date(date + ' ' + break_out) - 
  new Date(date + ' ' + time_in)
) / 1000 / 60 / 60;

var afternoon = (
  new Date( date + ' ' + time_out) - 
  new Date(date + ' ' + break_in)
) / 1000 / 60 / 60;

var total_time = morning + afternoon;  // total_time == 7.75

How to compute the .75 in 15 minutes?

2 个答案:

答案 0 :(得分:0)

I would approach it this way:

// The time stamps of your beginnings and endings
var timeIn = new Date(2018, 1, 3, 9, 15, 0);
var breakOut = new Date(2018, 1, 3, 12, 0, 0);
var breakIn = new Date(2018, 1, 3, 13, 0, 0);
var timeOut = new Date(2018, 1, 3, 18, 0, 0);

// Just calculate the hours as decimal - same as yours above
var morningHours = ( breakOut - timeIn ) / 1000 / 60 / 60;
var afternoonHours = ( timeOut - breakIn ) / 1000 / 60 / 60;

var timeDecimal = morningHours + afternoonHours;

// Now turn those decimal numbers into a nice syntax
// First get the amount of hours in seconds
var timeInSeconds = timeDecimal * 60 * 60;
var hours = Math.floor((timeInSeconds / (60 * 60)));

// Now subtract the hours (in seconds) from the full amount of seconds
var remainingMinutesInSeconds = timeInSeconds - (hours * 60 * 60);
// Turn the seconds into actual minutes
var minutes = Math.floor((remainingMinutesInSeconds / 60));
// Do a bit of formatting, so the result has leading zeros
if (hours < 10) {
    hours = "0" + hours;
}
if (minutes < 10) {
    minutes = "0" + minutes;
}

console.log("" + hours + ":" + minutes);

Okay, let's run through it. In my code, I already used a time stamp for the timeIn, breakOut, breakIn and timeOut values. Simply because you didn't say what the value of date was in your calculation. But you can keep your calculation as well!

It gets interesting with turning the decimal numbers into a nicer syntax. I tried to name the variables self-explanatory. First we turn the decimal hours into seconds and calculate the pure hours from it. That gives us the amount of hours - and we can use these hours in seconds to calculate the minutes as well.

The we can use those values to subtract the hours (calculated to seconds) from the full amount of seconds. That leaves us with the minutes (in seconds). Those seconds need to be turned into actual minutes.

After we did that we just have to do a bit of formatting.

答案 1 :(得分:0)

所以你有total_time = 7.75(无论你怎么得到它)。

只是做:

var total_hours = parseInt(total_time);
var total_minutes = parseInt(total_time % 1 * 60);