date.service.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Injectable } from "@angular/core";
  2. import {
  3. addDays,
  4. startOfWeek,
  5. endOfMonth,
  6. startOfDay,
  7. addMonths,
  8. startOfMonth,
  9. startOfYear,
  10. addYears,
  11. endOfYear,
  12. endOfWeek,
  13. } from "date-fns";
  14. @Injectable({
  15. providedIn: "root",
  16. })
  17. export class DateService {
  18. constructor() {}
  19. /**
  20. * 日期操作
  21. */
  22. date() {
  23. //获得上周的开始日期(上周一 00:00:00)
  24. function getLastWeekStartDate() {
  25. return addDays(startOfWeek(new Date()), -6);
  26. }
  27. //获得上周的结束日期(上周日 23:59:59)
  28. function getLastWeekEndDate() {
  29. return addDays(endOfWeek(new Date()), -6);
  30. }
  31. //获得上月开始时间(上月1号 00:00:00)
  32. function getLastMonthStartDate() {
  33. return startOfMonth(addMonths(new Date(), -1));
  34. }
  35. //获得上月结束时间(上月底 23:59:59)
  36. function getLastMonthEndDate() {
  37. return endOfMonth(addMonths(new Date(), -1));
  38. }
  39. //获得上年的开始日期(去年1月1日 00:00:00)
  40. function getLastYearStartDate() {
  41. return startOfYear(addYears(new Date(), -1));
  42. }
  43. //获得上年的结束日期(去年12月31日 23:59:59)
  44. function getLastYearEndDate() {
  45. return endOfYear(addYears(new Date(), -1));
  46. }
  47. return {
  48. lastWeekStartDate: getLastWeekStartDate(),
  49. lastWeekEndDate: getLastWeekEndDate(),
  50. lastMonthStartDate: getLastMonthStartDate(),
  51. lastMonthEndDate: getLastMonthEndDate(),
  52. lastYearStartDate: getLastYearStartDate(),
  53. lastYearEndDate: getLastYearEndDate(),
  54. };
  55. }
  56. }