startOf.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var clone = require('../lang/clone');
  2. /**
  3. * get a new Date object representing start of period
  4. */
  5. function startOf(date, period){
  6. date = clone(date);
  7. // intentionally removed "break" from switch since start of
  8. // month/year/etc should also reset the following periods
  9. switch (period) {
  10. case 'year':
  11. date.setMonth(0);
  12. /* falls through */
  13. case 'month':
  14. date.setDate(1);
  15. /* falls through */
  16. case 'week':
  17. case 'day':
  18. date.setHours(0);
  19. /* falls through */
  20. case 'hour':
  21. date.setMinutes(0);
  22. /* falls through */
  23. case 'minute':
  24. date.setSeconds(0);
  25. /* falls through */
  26. case 'second':
  27. date.setMilliseconds(0);
  28. break;
  29. default:
  30. throw new Error('"'+ period +'" is not a valid period');
  31. }
  32. // week is the only case that should reset the weekDay and maybe even
  33. // overflow to previous month
  34. if (period === 'week') {
  35. var weekDay = date.getDay();
  36. var baseDate = date.getDate();
  37. if (weekDay) {
  38. if (weekDay >= baseDate) {
  39. //start of the week is on previous month
  40. date.setDate(0);
  41. }
  42. date.setDate(date.getDate() - date.getDay());
  43. }
  44. }
  45. return date;
  46. }
  47. module.exports = startOf;