Reputation: 1472
I seem to not be getting it. I have number of days, say 762 which will be 2 years(730 days each 365 days), 1 month(762-730), and 2 days(assuming every month has constant 30 days)
I need to do that on JS. this what I came up with:
days = 762;
ymd = {
d: days % 30,
m: Math.floor((days - (days % 30)) / 30),
y: ((days - (days % 365)) / 365),
}
if (ymd.m > 12){
ymd.y += Math.floor(ymd.m / 12);
ymd.m = ymd.m % 12;
}
console.log(ymd);
Well it's not working.
Upvotes: 1
Views: 201
Reputation: 66394
Using your assumptions on year/month lengths;
function dToYMD(i) {
var y, m ,d;
y = (i / 365) | 0;
i = i - y * 365;
m = (i / 30) | 0;
i = i - m * 30;
d = i | 0;
return [y, m, d];
}
dToYMD(762); // [2 /* years */, 1 /* month */, 2 /* days */]
I thought there was something built in. i meant using Date obj
This would not use your assumptions for lengths, but you could set a date based upon the unix epoch, and then minus 1970
from the year.
function dToYMD(i) {
var d = new Date(i * 864e5);
return [d.getUTCFullYear() - 1970, d.getUTCMonth(), d.getUTCDate() - 1];
}
dToYMD(762); // [2 /* years */, 1 /* month */, 1 /* days */]
Note this time, the number of days is different because January has 31
days.
Upvotes: 3
Reputation: 609
Modulus (%
) returns the remainder after a division. You should be using regular division then flooring the value.
Like so:
var numOfDays = 762;
var years = Math.floor(numOfDays / 365),
months = Math.floor((numOfDays-(years*365)) / 30),
days = ((numOfDays-(years*365))-months*30);
Upvotes: 1