date.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. function isToday (d: Date) {
  2. const today = new Date()
  3. return areDatesEqual(d, today)
  4. }
  5. function isYesterday (d: Date) {
  6. const yesterday = new Date()
  7. yesterday.setDate(yesterday.getDate() - 1)
  8. return areDatesEqual(d, yesterday)
  9. }
  10. function isThisWeek (d: Date) {
  11. const minDateOfThisWeek = new Date()
  12. minDateOfThisWeek.setHours(0, 0, 0)
  13. // getDay() -> Sunday - Saturday : 0 - 6
  14. // We want to start our week on Monday
  15. let dayOfWeek = minDateOfThisWeek.getDay() - 1
  16. if (dayOfWeek < 0) dayOfWeek = 6 // Sunday
  17. minDateOfThisWeek.setDate(minDateOfThisWeek.getDate() - dayOfWeek)
  18. return d >= minDateOfThisWeek
  19. }
  20. function isThisMonth (d: Date) {
  21. const thisMonth = new Date().getMonth()
  22. return d.getMonth() === thisMonth
  23. }
  24. function isLastMonth (d: Date) {
  25. const now = new Date()
  26. return getDaysDifferences(now, d) <= 30
  27. }
  28. function isLastWeek (d: Date) {
  29. const now = new Date()
  30. return getDaysDifferences(now, d) <= 7
  31. }
  32. // ---------------------------------------------------------------------------
  33. export {
  34. isYesterday,
  35. isThisWeek,
  36. isThisMonth,
  37. isToday,
  38. isLastMonth,
  39. isLastWeek
  40. }
  41. // ---------------------------------------------------------------------------
  42. function areDatesEqual (d1: Date, d2: Date) {
  43. return d1.getFullYear() === d2.getFullYear() &&
  44. d1.getMonth() === d2.getMonth() &&
  45. d1.getDate() === d2.getDate()
  46. }
  47. function getDaysDifferences (d1: Date, d2: Date) {
  48. return (d1.getTime() - d2.getTime()) / (86400000)
  49. }