如何将十进制小时值转换为 hh:mm:ss

How to convert decimal hour value to hh:mm:ss

本文关键字:hh mm ss 转换 十进制 小时      更新时间:2023-09-26

如何在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;

与其自己进行计算,不如使用内置功能在 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));

你可以做这样的事情:

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);

我发现这个函数在将我的十进制值秒转换为标准时间字符串 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"

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

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)

请注意,这不是为超过一个月的小时值设计的。

符合我的目的

function formatHoursMinutesSeconds(num){
  var hours = Math.floor(num * 24);
  var minutes = Math.floor(((num * 24) - hours) * 60);
  var seconds = Math.floor(((((num * 24) - hours) * 60)-minutes)*60);
  return (hours + ":" + minutes.toString().padStart(2, '0') + ":" + 
  seconds.toString().padStart(2, '0'));
 }