【问题标题】:How to convert decimal hour value to hh:mm:ss如何将十进制小时值转换为 hh:mm:ss
【发布时间】:2016-05-29 08:52:33
【问题描述】:

如何在 jquery 或 javascript 中将十进制小时值(如 1.6578)转换为 hh:mm:ss?

我只设法使用此代码对 hh:mm 执行此操作:

var decimaltime= "1.6578";
var hrs = parseInt(Number(decimaltime));
var min = Math.round((Number(decimaltime)-hrs) * 60);
var clocktime = hrs+':'+min;

【问题讨论】:

标签: javascript jquery date


【解决方案1】:

与其自己进行计算,不如使用内置功能来设置 Date 对象的任意日期的秒数,将其转换为字符串,并去掉日期部分,只留下 hh:mm:ss 字符串.

var decimalTimeString = "1.6578";
var n = new Date(0,0);
n.setSeconds(+decimalTimeString * 60 * 60);
document.write(n.toTimeString().slice(0, 8));

【讨论】:

  • 如果只需要小时和分钟(hh:mm),可以使用n.setMinutes(+decimalTimeString * 60); var result = n.toTimeString().slice(0, 5);
【解决方案2】:

你可以这样做:

var decimalTimeString = "1.6578";
var decimalTime = parseFloat(decimalTimeString);
decimalTime = decimalTime * 60 * 60;
var hours = Math.floor((decimalTime / (60 * 60)));
decimalTime = decimalTime - (hours * 60 * 60);
var minutes = Math.floor((decimalTime / 60));
decimalTime = decimalTime - (minutes * 60);
var seconds = Math.round(decimalTime);
if(hours < 10)
{
	hours = "0" + hours;
}
if(minutes < 10)
{
	minutes = "0" + minutes;
}
if(seconds < 10)
{
	seconds = "0" + seconds;
}
alert("" + hours + ":" + minutes + ":" + seconds);

【讨论】:

    【解决方案3】:

    我发现这个函数在将我的十进制秒值转换为标准时间字符串 hh:mm:ss 方面效果很好

    function formatDuration(seconds) {
      return new Date(seconds * 1000).toISOString().substring(11, 11 + 8);
    }
    const secondsInDecimal = 1.6578;
    formatDuration(secondsInDecimal);
    
    // "00:00:01"
    

    参考资料:

    流程:

    1. new Date(seconds * 1000) 返回此字符串 "Wed Dec 31 1969 19:00:01 GMT-0500 (Eastern Standard Time)"
    2. toISOString() 是 Date 对象上的一个方法,它将返回的字符串更改为 "1970-01-01T00:00:01.657Z"。这是从上面 #1 返回的简化字符串。
    3. 在该字符串上运行 substring() 会返回它的一部分,从第 11 个索引开始,长度为 8 个索引(索引)。该值为"00:00:01"

    【讨论】:

      【解决方案4】:

      我意识到这并不是原始海报所需要的,但我需要从十进制时间中获取天、小时和分钟,然后我可以将其用于计算和设置日期对象。许多其他帖子正在使用涉及字符串和切片等的过时方法。

      const decimalHours = 27.33;
      const n = new Date(0,0);
      n.setMinutes(+Math.round(decimalHours * 60)); 
      const days = (n.getDate() - 1)
      const hours = n.getHours()
      const minutes = n.getMinutes()
      console.log("Days: ",days, "Hours: ",hours, "Minutes: ",minutes)

      const decimalHours = 4.33;
      const n = new Date(0,0);
      n.setMinutes(+Math.round(decimalHours * 60)); 
      const days = (n.getDate() - 1)
      const hours = n.getHours()
      const minutes = n.getMinutes()
      console.log("Days: ",days, "Hours: ",hours, "Minutes: ",minutes)

      请注意,这不适用于超过一个月的小时值。

      【讨论】:

        猜你喜欢
        • 2013-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        相关资源
        最近更新 更多