Skip to content

Instantly share code, notes, and snippets.

@ivancorrales
Last active March 14, 2016 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivancorrales/c23359642d01af4716ae to your computer and use it in GitHub Desktop.
Save ivancorrales/c23359642d01af4716ae to your computer and use it in GitHub Desktop.
calculate days and months from a month and a number of days
var task = (function(){
var _days = [31,28,31,30,31,30,31,31,30,31,30,31];
function addDays(date,days){
date.setDate(date.getDate() + days);
return date;
}
function isLeapYear(year){
return year % 4 === 0 ;
}
function subtractDaysByMonthAndYear(currentMonth,numberOfDays){
var days = numberOfDays-_days[currentMonth.month];
if(currentMonth.month==1 && isLeapYear(currentMonth.year))
days -=1;
return days;
}
function increaseMonth(currentMonth){
if(currentMonth.month>11){
currentMonth.month=0;
currentMonth.year++;
}
return currentMonth;
}
return {
fromMonth: function fromMonth(currentMonth,numberOfDays,monthsCounter){
monthsCounter = monthsCounter || 0;
currentMonth = increaseMonth(currentMonth);
var days = subtractDaysByMonthAndYear(currentMonth,numberOfDays);
currentMonth.month++;
return (_days[currentMonth.month]>=days) ? [++monthsCounter,days] : fromMonth(currentMonth,days,++monthsCounter);
},
addDays: function(date,days){
return addDays(date,days);
}
};
})();
var currentMonth = {
month:2,
year:2016
};
console.log(task.fromMonth(currentMonth,1100));
currentMonth = {
month:2,
year:2015
};
console.log(task.fromMonth(currentMonth,1100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment