Skip to content

Instantly share code, notes, and snippets.

@jamesona
Last active January 8, 2016 21:19
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 jamesona/0f6e3a86193079608b13 to your computer and use it in GitHub Desktop.
Save jamesona/0f6e3a86193079608b13 to your computer and use it in GitHub Desktop.
var getBeginningDate = function(period, date){
var date = (date === undefined ? new Date() : new Date(date));
if (period) {
period = period.toLowerCase();
switch (period) {
case 'year':
date.setMonth(0);
case 'quarter':
if (date.getMonth() >= 9) {
date.setMonth(9);
} else if (date.getMonth() < 9 && date.getMonth() >= 6) {
date.setMonth(6);
} else if (date.getMonth() < 6 && date.getMonth() >= 3) {
date.setMonth(3);
} else {
date.setMonth(0);
}
case 'month':
date.setDate(1);
case 'week':
if (date.getDate() > 1) date.setDate(Math.max(0, date.getDate() - date.getDay()));
case 'day':
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
} else {
date = getBeginningDate('year');
}
return new Date(date.valueOf());
}
var getEndDate = function(period, date){
var date = (date === undefined ? new Date() : new Date(date));
if (period) {
period = period.toLowerCase();
switch (period) {
case 'year':
date.setMonth(11);
case 'quarter':
if (date.getMonth() >= 9) {
date.setMonth(11);
} else if (date.getMonth() < 9 && date.getMonth() >= 6) {
date.setMonth(8);
} else if (date.getMonth() < 6 && date.getMonth() >= 3) {
date.setMonth(5);
} else {
date.setMonth(2);
}
case 'month':
var month = date.getMonth(), year = date.getFullYear();
if ([0, 2, 4, 6, 7, 9, 11].indexOf(month) ) {
date.setDate(31);
}
else if (month === 1) {
date.setDate((((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 ));
}
else {
date.setDate(30);
}
case 'week':
if (date.getDay() < 6) {
var newdate = new Date(date);
newdate.setDate(date.getDate() + 6 - date.getDay());
if (newdate.getFullYear() <= date.getFullYear() || period == 'week') date = newdate;
}
case 'day':
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
date.setMilliseconds(999);
}
} else {
date = getEndDate('year');
}
return new Date(date.valueOf());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment