【问题标题】:how to calculate hour difference in 2 decimals behind dot如何计算点后面2位小数的小时差
【发布时间】:2021-08-21 09:56:18
【问题描述】:

这是我的表格:

<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。 如何获得点后两位小数的小时数?

【问题讨论】:

    标签: javascript date time


    【解决方案1】:

    在计算中不只使用小时数。您也需要至少几分钟,但您也可以使用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 相同,但返回毫秒值而不是日期对象。)

    请注意,我稍微更改了字符串格式(Year-Month-DayT,而不是空格),所以字符串在 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 &lt; 0) 检查结束时间是否真的可能在开始时间之前,但您将它们保存在原件中,所以我想我应该将它们留在那里。如果结束时间不能早于开始时间,您可以安全地删除它们。

    【讨论】:

    • Date.parse("01-01-2021T" + "15:00") 在 Safari 中返回 NaN。也许您的意思是日期部分是“2021-01-01T”?
    • @RobG - OMG。谢谢!!我记得当时关于那根绳子的一些事情一直困扰着我,但我从来没有完全把它放在心上。
    • 我已经明白了。谢谢解决方案
    【解决方案2】:

    有一个稍微不同的方法,但结果是一样的。

      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;
    }
    &lt;output id="result" name="result"&gt;&lt;/output&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多