Skip to content

Instantly share code, notes, and snippets.

@furf
Created June 4, 2009 16:00
Show Gist options
  • Save furf/123683 to your computer and use it in GitHub Desktop.
Save furf/123683 to your computer and use it in GitHub Desktop.
Utility for flooring a date to a specified level
function floorDate (floor /*, date, clone */) {
var clone = (arguments[2] === true),
date = (typeof arguments[1] !== 'undefined') ? arguments[1] : new Date();
if (clone || !(date instanceof Date)) {
date = new Date(date);
}
switch(floor) {
case 'year': date.setMonth(0);
case 'month':
case 'week': date.setDate(floor === 'week' ? date.getDate() - date.getDay() + floorDate.firstDayOfWeek: 1);
case 'day': date.setHours(0);
case 'hour': date.setMinutes(0);
case 'minute': date.setSeconds(0);
default: date.setMilliseconds(0);
}
return date;
}
floorDate.firstDayOfWeek = 0;
new Date(2009, 1, 2, 3, 4, 5);
// Mon Feb 02 2009 03:04:05 GMT-0500 (EST)
floorDate('year', new Date(2009, 1, 2, 3, 4, 5));
// Thu Jan 01 2009 00:00:00 GMT-0500 (EST)
floorDate('month', new Date(2009, 1, 2, 3, 4, 5));
// Sun Feb 01 2009 00:00:00 GMT-0500 (EST)
floorDate('day', new Date(2009, 1, 2, 3, 4, 5));
// Mon Feb 02 2009 00:00:00 GMT-0500 (EST)
floorDate('hour', new Date(2009, 1, 2, 3, 4, 5));
// Mon Feb 02 2009 03:00:00 GMT-0500 (EST)
floorDate('minute', new Date(2009, 1, 2, 3, 4, 5));
// Mon Feb 02 2009 03:04:00 GMT-0500 (EST)
floorDate('second', new Date(2009, 1, 2, 3, 4, 5));
// Mon Feb 02 2009 03:04:05 GMT-0500 (EST)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment