我想将时间长度(即秒数)转换为冒号分隔的时间字符串(hh:mm:ss)。
我在这里找到了一些有用的答案,但它们都是关于转换为x小时和x分钟格式的。
那么有没有一个小片段可以在jQuery或纯JavaScript中实现此操作?
我想将时间长度(即秒数)转换为冒号分隔的时间字符串(hh:mm:ss)。
我在这里找到了一些有用的答案,但它们都是关于转换为x小时和x分钟格式的。
那么有没有一个小片段可以在jQuery或纯JavaScript中实现此操作?
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
alert("5678".toHHMMSS());
工作示例:
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours + ':' + minutes + ':' + seconds;
}
console.log("5678".toHHMMSS());
var currentDate = new Date();
var year = currentDate.getFullYear();
var month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
var day = ('0' + currentDate.getDate()).slice(-2);
var formattedDate = year + '-' + month + '-' + day;
console.log(formattedDate);
var date = new Date(0);
date.setSeconds(45); // specify value for SECONDS here
var timeString = date.toISOString().substring(11, 19);
console.log(timeString)
new Date(1000 * seconds).toISOString().substr(11, 8)
。 - Bohumir Zamecniksubstr
后面使用 .replace(/^[0:]+/, "")
,以删除字符串开头的所有零和冒号。 - Palo为了以 hh:MM:ss
格式获取时间部分,您可以使用以下正则表达式:
(此前在同一帖子中有人提到过,感谢那位用户。)
var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
console.log(myDate)
var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2})(:\d{2}).*/, "$1");
- Topher Fangioreplace
方法让人感到困惑。为什么不使用new Date(null, null, null, null, null, timeInSeconds).toTimeString().match(/\d{2}:\d{2}:\d{2}/)[0]
呢? - Călin Darienew Date().toLocaleTimeString('en-US', {hour12: false}).split(':')[0]
。 - Henrik N我建议使用普通的JavaScript,使用Date对象。(如果要使用更短的解决方案,请参见第二个代码片段中使用toTimeString
的方法。)
var seconds = 9999;
// multiply by 1000 because Date() requires miliseconds
var date = new Date(seconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
// If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
// if (hh > 12) {hh = hh % 12;}
// These lines ensure you have two-digits
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
if (ss < 10) {ss = "0"+ss;}
// This formats your string to HH:MM:SS
var t = hh+":"+mm+":"+ss;
document.write(t);
当然,创建的 Date 对象将与实际日期关联,但对于这些目的来说,该数据是无关紧要的,因此您不必担心它。
利用 toTimeString
函数并在空格上分割:
var seconds = 9999; // Some arbitrary value
var date = new Date(seconds * 1000); // multiply by 1000 because Date() requires miliseconds
var timeStr = date.toTimeString().split(' ')[0];
toTimeString
返回的是 '16:54:58 GMT-0800 (PST)'
,将其以第一个空格为分隔符进行拆分即可得到 '16:54:58'
。
date.getUTCHours()
和 date.getUTCMinutes()
,我会得到一个正确的结果。 - mivkfunction formatTime(ms: number) {
const seconds = Math.floor(Math.abs(ms / 1000))
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
const s = Math.round(seconds % 60)
const t = [h, m > 9 ? m : h ? '0' + m : m || '0', s > 9 ? s : '0' + s]
.filter(Boolean)
.join(':')
return ms < 0 && seconds ? `-${t}` : t
}
import assert from 'assert'
assert.equal(formatTime(0), '0:00')
assert.equal(formatTime(1_000), '0:01')
assert.equal(formatTime(599_000), '9:59')
assert.equal(formatTime(600_000), '10:00')
assert.equal(formatTime(3600_000), '1:00:00')
assert.equal(formatTime(360009_000), '100:00:09')
assert.equal(formatTime(200), '0:00')
assert.equal(formatTime(-200), '0:00')
assert.equal(formatTime(-1_000), '-0:01')
const s = Math.round(seconds % 60);
。 - Raff谷歌搜索得到了这个结果:
function secondsToTime(secs)
{
secs = Math.round(secs);
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
secondsToTime(119.9)
=> Object {h: 0, m: 1, s: 60}
。为了修复这个 bug,在方法开头加入 secs = Math.round(secs);
。当然,在演示中我们就已经发现了这个问题... - Benjamin Crouzier同一主题的变体。对单个数字秒数进行了稍微不同的处理。
seconds2time(0) -> "0s"
seconds2time(59) -> "59s"
seconds2time(60) -> "1:00"
seconds2time(1000) -> "16:40"
seconds2time(4000) -> "1:06:40"
function seconds2time (seconds) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor((seconds - (hours * 3600)) / 60);
var seconds = seconds - (hours * 3600) - (minutes * 60);
var time = "";
if (hours != 0) {
time = hours+":";
}
if (minutes != 0 || time !== "") {
minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
time += minutes+":";
}
if (time === "") {
time = seconds+"s";
}
else {
time += (seconds < 10) ? "0"+seconds : String(seconds);
}
return time;
}
function formatTime(seconds) {
return [
parseInt(seconds / 60 / 60),
parseInt(seconds / 60 % 60),
parseInt(seconds % 60)
]
.join(":")
.replace(/\b(\d)\b/g, "0$1")
}
parseInt
替换为Math.floor
(parseInt
应该有字符串输入)。 - Aaron Bseconds
必须是一个字符串。在TypeScript中,如果seconds
是一个数字,请使用Math.floor
代替parseInt
。 - Lee GoddardparseInt
,并在 .join(':')
之前加上 .map(Math.floor)
。此外,为了更好的可读性,可以在 .join()
之前使用 .map(n => n.toString().padStart(2, '0'))
替换 .replace(/\b(\d)\b/g, "0$1")
。 - Chris我喜欢第一个答案。 有一些优化:
源数据是数字,无需进行额外的计算。
计算过度了。
结果代码:
Number.prototype.toHHMMSS = function () {
var seconds = Math.floor(this),
hours = Math.floor(seconds / 3600);
seconds -= hours*3600;
var minutes = Math.floor(seconds / 60);
seconds -= minutes*60;
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
使用令人惊叹的moment.js库:
function humanizeDuration(input, units ) {
// units is a string with possible values of y, M, w, d, h, m, s, ms
var duration = moment().startOf('day').add(units, input),
format = "";
if(duration.hour() > 0){ format += "H [hours] "; }
if(duration.minute() > 0){ format += "m [minutes] "; }
format += " s [seconds]";
return duration.format(format);
}
这使您可以指定任何持续时间,无论是小时、分钟、秒还是毫秒,并返回一个易于阅读的版本。