本文介绍了将以秒为单位的时间间隔转换为更易读的形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个代码片段,用于将按秒数给出的时间量转换为某种人类可读的形式.该函数应该接收一个数字并输出一个像这样的字符串:
I need a code snippet for converting amount of time given by number of seconds into some human readable form. The function should receive a number and output a string like this:
34 seconds
12 minutes
4 hours
5 days
4 months
1 year
无需格式化,硬编码格式即可.
No formatting required, hard-coded format will go.
推荐答案
在 Royi 的帮助下,我们得到了以人类可读的形式输出时间间隔的代码:
With help of Royi we've got code that outputs time interval in a human readable form:
function millisecondsToStr (milliseconds) {
// TIP: to find current time in milliseconds, use:
// var current_time_milliseconds = new Date().getTime();
function numberEnding (number) {
return (number > 1) ? 's' : '';
}
var temp = Math.floor(milliseconds / 1000);
var years = Math.floor(temp / 31536000);
if (years) {
return years + ' year' + numberEnding(years);
}
//TODO: Months! Maybe weeks?
var days = Math.floor((temp %= 31536000) / 86400);
if (days) {
return days + ' day' + numberEnding(days);
}
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) {
return hours + ' hour' + numberEnding(hours);
}
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) {
return minutes + ' minute' + numberEnding(minutes);
}
var seconds = temp % 60;
if (seconds) {
return seconds + ' second' + numberEnding(seconds);
}
return 'less than a second'; //'just now' //or other string you like;
}
这篇关于将以秒为单位的时间间隔转换为更易读的形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!