Created
October 1, 2015 13:21
-
-
Save Madrigal/5bbc7e6e64183cfcc0ec to your computer and use it in GitHub Desktop.
A snippet to know when is the next pay day
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Snippet to know when is the next pay day (quincena) | |
// The rules are: | |
// -Pay day is on the 15th and the last day of the month | |
// -- If that day is not a weekday (Mon-Fri) pay day falls on the previous Friday | |
// Of course, without additional effort this won't take into consideration holidays | |
// January is 0 and so on | |
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]; | |
function isLeapYear(year) { | |
return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0); | |
} | |
function getDaysInMonth(month, year) { | |
// Special case for February | |
if (month == 1 && isLeapYear(year)) { | |
return 29; | |
} | |
return daysInMonth[month]; | |
} | |
// Gets the next 15th or last day of the month, whichever is closer | |
function getNextPayDate (d) { | |
var dayOfTheMonth = d.getDate(); | |
if (dayOfTheMonth == 15) { | |
return d; | |
} | |
if (dayOfTheMonth < 15) { | |
d.setDate(15); | |
return d; | |
} | |
var lastDayOfTheMonth = getDaysInMonth(d.getMonth(), d.getFullYear()); | |
d.setDate(lastDayOfTheMonth); | |
return d; | |
} | |
function isWeekDay(day) { | |
// Sunday is 0, Saturday is 6 | |
return day !== 0 && day !== 6; | |
} | |
function getEarliestFriday(d) { | |
var dayOfTheWeek = d.getDay(); | |
if (dayOfTheWeek == 5) { | |
return d; | |
} | |
// How many days do we have to go back? | |
// alternative is (d - 5 + 7) % 7 | |
var daysToGoBack; | |
if (dayOfTheWeek >= 5) { | |
daysToGoBack = dayOfTheWeek - 5; | |
} else { | |
daysToGoBack = dayOfTheWeek + 2; | |
} | |
d.setDate(d.getDate() - daysToGoBack); | |
return d; | |
} | |
function getNextQuincena(d) { | |
var nextPayDate = getNextPayDate(d); | |
if (!isWeekDay(nextPayDate.getDay())) { | |
return getEarliestFriday(nextPayDate); | |
} | |
return nextPayDate; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment