Convert days to weeks and days

Hello

I need some help about converting days to weeks and remaining days.

For example :

Total days : 152 = 147 Weeks and 5 Days:

so I want to write a function getWeeks(152) and it will return an array of 3 elements 0 will be weeks and 1 will be days.

Please help
Zeeshan

You didn’t say what you wanted returned in the third entry in the array but here’s the function that returns weeks in element zero and left over days in element one.

function getWeeks(d) {
a[0] = Math.floor(d/7);
a[1] = d%7;
return a;
}

It might be more meaningful to return a basic object instead.

function getWeeks(days) {
  return {
    weeks : Math.floor(days / 7),
    days : days % 7
  };
}

Then you can use it like so:

var obj = getWeeks(152);
alert(obj.weeks); // alerts '21'
alert(obj.days); // alerts '5'

Using objects is usually a bit nicer, and the intent of the values is more obvious, especially in more complex objects and when it’s been six months or so since you last looked at the code. ‘obj.weeks’ is a lot more meaningful at a glance than ‘obj[0]’.

Cheers,
D.

Wow !

Thanks a lot !

@felgall
I dont have words for you. All I can say is that Javascript Guru is a very small badge for you. For me, you are JAVASCRIPT !

@disgracian
Thanks for your feed back !

If that were true, we could add bits to him by calling his prototype object. I don’t know if he’d like that.

Cheers,
D.