如何使用JavaScript将秒数转换为HH-MM-SS
格式的字符串?
如何使用JavaScript将秒数转换为HH-MM-SS
格式的字符串?
<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>
已经有很多答案了,但我的要求是:
const seconds2duration = ( seconds, decimals=0 ) => {
let fraction = ( seconds - Math.floor( seconds ) ).toFixed( decimals );
fraction = decimals === 0 ? '' : fraction.slice( 1 );
const [ hours, mins, secs ] = [ seconds / 3600, seconds % 3600 / 60, seconds % 3600 % 60 ].map( ( x ) => String( Math.floor( x ) ).padStart( 2, '0' ) );
if ( hours === '00' && mins === '00' ) {
return secs + fraction;
} else if ( hours === '00' ) {
return [ mins, secs + fraction ].join( ':' );
} else {
return [ hours, mins, secs + fraction ].join( ':' );
}
};
console.log(seconds2duration(25*3600 + 0*60 + 41 + 0.333, 0)); // 25:00:41
console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 0)); // 05:41
console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 1)); // 05:41.3
console.log(seconds2duration(0*3600 + 0*60 + 41 + 0.333, 2)); // 41.33
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;
}
// For Example :
alert("186".toHHMMSS());
const secondsTo_HHMMSS = (seconds) => {
//format to a readable friendly timer
let hour = Math.floor(seconds / 3600);
let minute = Math.floor((seconds % 3600) / 60);
let second = seconds % 60;
if(hour.toString().length === 1) {
hour = `0${hour}`;
}
if(minute.toString().length === 1) {
minute = `0${minute}`;
}
if(second.toString().length === 1) {
second = `0${second}`;
};
let timer = `${hour}-${minute}-${second}`;
return timer;
}
const timeFormat = new Intl.DateTimeFormat('es-US', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
timeZone: 'UTC'
});
const endTimeFormatted = timeFormat.format(new Date(SECS * 1000); //hour in secs
虽然这是相当简单的任务,但你们中的一些人直接推荐了 Moment.js,或编写了一些最丑陋的函数来解析一些秒数...
transform(time: number): string {
if (time != null) {
const hours: number = Math.floor(time / 3600);
const minutes: number = Math.floor((time - (hours * 3600)) / 60);
const seconds: number = time - (hours * 3600) - (minutes * 60);
return [hours, (minutes < 10) ? '0' + minutes : minutes, (seconds < 10) ? '0' + seconds : seconds].join(':');
} else {
return '00:00:00';
}
}
这将在任何情况下都能正常工作...
我以前使用过这段代码来创建一个简单的时间段对象:
function TimeSpan(time) {
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
while(time >= 3600)
{
this.hours++;
time -= 3600;
}
while(time >= 60)
{
this.minutes++;
time -= 60;
}
this.seconds = time;
}
var timespan = new Timespan(3662);