假设我有一个数字代表从开始时间到现在的分钟数。
我想创建一个函数,它返回与传递给该函数的分钟相对应的年,月,周和日。
这是一个例子:
var minutes = 635052; // 635052 = (24*60)*365 + (24*60)*30*2 + (24*60)*14 + (24*60)*2 + 12;
getDataHR(minutes); // 1 year, 2 months, 2 week, 2 days, 12 minutes
function getDataHR (newMinutes) {
minutes = newMinutes;
.......
return hrData; // 1 year, 2 months, 2 week, 2 days, 12 minutes
}
实现结果的最佳方法是什么?
答案 0 :(得分:12)
也许是这样的?
var units = {
"year": 24*60*365,
"month": 24*60*30,
"week": 24*60*7,
"day": 24*60,
"minute": 1
}
var result = []
for(var name in units) {
var p = Math.floor(value/units[name]);
if(p == 1) result.push(p + " " + name);
if(p >= 2) result.push(p + " " + name + "s");
value %= units[name]
}
答案 1 :(得分:6)
建立thg435's response above,我创建了一个将秒转换为天,小时,分钟和秒的函数:
function secondsToString(seconds)
{
var value = seconds;
var units = {
"day": 24*60*60,
"hour": 60*60,
"minute": 60,
"second": 1
}
var result = []
for(var name in units) {
var p = Math.floor(value/units[name]);
if(p == 1) result.push(" " + p + " " + name);
if(p >= 2) result.push(" " + p + " " + name + "s");
value %= units[name]
}
return result;
}
我还在结果中添加了一些空格,以便为逗号留出一些空间。输出如下:
1 day, 3 hours, 52 minutes, 7 seconds.
答案 2 :(得分:5)
我是这样做的,因为我甚至不知道javascript中有模运算符:
var minutes = 635052; // 635052 = (24*60)*365 + (24*60)*30*2 + (24*60)*14 + (24*60)*2 + 12;
getDataHR(minutes); // 1 year, 2 months, 2 week, 2 days, 12 minutes
function getDataHR (newMinutes) {
MINS_PER_YEAR = 24 * 365 * 60
MINS_PER_MONTH = 24 * 30 * 60
MINS_PER_WEEK = 24 * 7 * 60
MINS_PER_DAY = 24 * 60
minutes = newMinutes;
years = Math.floor(minutes / MINS_PER_YEAR)
minutes = minutes - years * MINS_PER_YEAR
months = Math.floor(minutes / MINS_PER_MONTH)
minutes = minutes - months * MINS_PER_MONTH
weeks = Math.floor(minutes / MINS_PER_WEEK)
minutes = minutes - weeks * MINS_PER_WEEK
days = Math.floor(minutes / MINS_PER_DAY)
minutes = minutes - days * MINS_PER_DAY
return years + " year(s) " + months + " month(s) " + weeks + " week(s) " + days + " day(s) " + minutes + " minute(s)"
//return hrData; // 1 year, 2 months, 2 week, 2 days, 12 minutes
}
答案 3 :(得分:4)
你需要使用除法和模数:
function getDataHR (newMinutes) {
var hrData = "";
var years = minutes / YEAR_IN_MINUTES; // int division = no remainder
hrData += years + "years";
minutes = minutes % YEAR_IN_MINUTES;
// ... continue for months, weeks, days, hours, etc. in that order
return hrData; // 1 year, 2 months, 2 week, 2 days, 12 minutes
}