Let’s suppose I have a number which represents the minutes passed from the start time to now.
I wan to create a function which returns the years, months, week and days corresponding to the minutes I am passing to that function.
Here an example:
JavaScript
x
9
1
var minutes = 635052; // 635052 = (24*60)*365 + (24*60)*30*2 + (24*60)*14 + (24*60)*2 + 12;
2
getDataHR(minutes); // 1 year, 2 months, 2 week, 2 days, 12 minutes
3
4
function getDataHR (newMinutes) {
5
minutes = newMinutes;
6
.
7
return hrData; // 1 year, 2 months, 2 week, 2 days, 12 minutes
8
}
9
What is the best way to achieve the result?
Advertisement
Answer
Maybe like this?
JavaScript
1
18
18
1
var units = {
2
"year": 24*60*365,
3
"month": 24*60*30,
4
"week": 24*60*7,
5
"day": 24*60,
6
"minute": 1
7
}
8
9
var result = []
10
11
for(var name in units) {
12
var p = Math.floor(value/units[name]);
13
if(p == 1) result.push(p + " " + name);
14
if(p >= 2) result.push(p + " " + name + "s");
15
value %= units[name]
16
17
}
18