如何计算点后两位小数的时差

how to calculate hour difference in 2 decimals behind dot

这是我的表格:

<input type="text" class="date" name="date[]">                      
<input type="text" class="starttime" name="starttime[]">

<input type="text" class="endtime" name="endtime[]">                        
<input type="text" class="hours" name="hours[]">

要计算 starttimeendtime 之间的小时数,我使用这个 js:

$('.endtime').on('change', function() {      
    //get values
    var date = $('.date').val();
    var starttime = $('.starttime').val();
    var endtime = $('.endtime').val();
      
    //create date format          
    var timeStart = new Date("01-01-2021 " + starttime).getHours();
    var timeEnd = new Date("01-01-2021 " + endtime).getHours();
     
    //console.log(timeStart, timeEnd);
    var hourDiff = timeEnd - timeStart;
    if (hourDiff < 0) {
        hourDiff = 24 + hourDiff;
    }
    
     $(".hours").val(hourDiff);  // output in input field          
});

假设开始时间是 12:00,结束时间是 15:45,输出应该是 3.75,但它显示 3。 我怎样才能得到小数点后两位小数的小时数?

通过在计算中不只使用小时数。您也需要至少几分钟,但您也可以使用 Date(毫秒)的完整分辨率:

// Get the milliseconds-since-The-Epoch values for the times on 01/01/2021
const timeStart = Date.parse("2021-01-01T" + starttime);
const timeEnd = Date.parse("2021-01-01T" + endtime);

// Calculate the difference, divide to get a fractional hours value
let hourDiff = (timeEnd - timeStart) / 1000 / 60 / 60;
if (hourDiff < 0) {
    hourDiff += 24;
}

// Format it to two decimals for display
$(".hours").val(hourDiff.toFixed(2));

Date.parse 的解析方式与 new Date 相同,但 returns 是自纪元以来的毫秒值而不是日期对象。)

请注意,我稍微更改了字符串格式(Year-Month-DayT 而不是 space),因此字符串在 the standard format 中。

实例:

function example(starttime, endtime) {
    // Get the milliseconds-since-The-Epoch values for the times on 01/01/2021
    const timeStart = Date.parse("2021-01-01T" + starttime);
    const timeEnd = Date.parse("2021-01-01T" + endtime);

    // Calculate the difference, divide to get a fractional hours value
    let hourDiff = (timeEnd - timeStart) / 1000 / 60 / 60;
    if (hourDiff < 0) {
        hourDiff += 24;
    }

    // Format it to two decimals for display
    console.log(starttime, "to", endtime, "=>", hourDiff.toFixed(2));
}

example("12:00", "15:45");
example("12:00", "03:45");

或者,直接转换时间:

function toHours(time) {
    const parts = time.split(":");
    const hours = Number(parts[0]) || 0;
    const minutes = Number(parts[1]) || 0;
    const seconds = Number(parts[2]) || 0;
    return hours + (minutes / 60) + (seconds / 3600);
}

然后

// Format it to two decimals for display
let hourDiff = toHours(endtime) - toHours(starttime);
if (hourDiff < 0) {
    hourDiff += 24;
}
$(".hours").val(hourDiff.toFixed(2));

实例:

function toHours(time) {
    const parts = time.split(":");
    const hours = Number(parts[0]) || 0;
    const minutes = Number(parts[1]) || 0;
    const seconds = Number(parts[2]) || 0;
    return hours + (minutes / 60) + (seconds / 3600);
}

function example(starttime, endtime) {
    let hourDiff = toHours(endtime) - toHours(starttime);
    if (hourDiff < 0) {
        hourDiff += 24;
    }

    console.log(starttime, "to", endtime, "=>", hourDiff.toFixed(2));
}

example("12:00", "15:45");
example("12:00", "03:45");
example("12:00", "3:45");

我想如果是我,我会这样做而不是使用 Date 对象。更直接。


您只需要那些 if (hourDiff < 0) 检查结束时间是否真的有可能早于开始时间,但您的原件中有它们,所以我想我应该把它们留在那里。如果结束时间不能早于开始时间,您可以安全地删除它们。

方法略有不同,但结果是一样的。

  const starttime = '12:00';
  const endtime = '15:45';

  const splitST = starttime.split(':');
  const splitET = endtime.split(':');

  const timeStart = new Date(2021, 0, 1, splitST[0], splitST[1]).getTime();
  const timeEnd = new Date(2021, 0, 1, splitET[0], splitET[1]).getTime();

  const hourDiff = timeEnd - timeStart;
  // Get the hours and rounded it to less than a given number
  const getHours = Math.floor(hourDiff / 1000 / 3600);
  // Get the remainder of dividing
  const getMinutes = (hourDiff / 1000 / 60) % 60;

const output = document.getElementById('result');

const starttime = '12:00';
const endtime = '15:45';

const splitST = starttime.split(':');
const splitET = endtime.split(':');

const timeStart = new Date(2021, 0, 1, splitST[0], splitST[1]).getTime();
const timeEnd = new Date(2021, 0, 1, splitET[0], splitET[1]).getTime();

const hourDiff = timeEnd - timeStart;
// Get the hours and rounded it to less than a given number
const getHours = Math.floor(hourDiff / 1000 / 3600);
// Get the remainder of dividing
const getMinutes = (hourDiff / 1000 / 60) % 60;

output.textContent = `${getHours} : ${getMinutes}`;
body {
  min-height: 100vh;
  display: grid;
  place-items: center;
}

output {
  margin-left: 15px;
  padding: 5px 15px;
  border-radius: 10px;
  border: 2px solid black;
  font-size: 1.5rem;
}
<output id="result" name="result"></output>