Skip to content
Advertisement

Converts minutes into days, week, months and years

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:

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
}

What is the best way to achieve the result?

Advertisement

Answer

Maybe like this?

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]

}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement