1+ const UNIT_DAY = 24 * 60 * 60 * 1000 ;
2+ const UNIT_WEEK = 7 * UNIT_DAY ;
3+ const UNIT_MONTH = 30 * UNIT_DAY ;
4+
5+ /**
6+ * Calculates the difference between the target date and today in the specified unit.
7+ *
8+ * @param {Date } targetDate - The date to compare with today.
9+ * @param {number } unit - The unit to use for the difference calculation (e.g., milliseconds per day).
10+ * @returns {number } The difference in the specified unit.
11+ */
12+ function ago ( targetDate , unit ) {
13+ const today = new Date ( ) ;
14+ today . setHours ( 0 , 0 , 0 , 0 ) ;
15+ targetDate . setHours ( 0 , 0 , 0 , 0 ) ;
16+ const differenceMs = today . getTime ( ) - targetDate . getTime ( ) ;
17+ const differenceDays = Math . floor ( differenceMs / unit ) ;
18+ return differenceDays ;
19+ }
20+
21+ /**
22+ * Calculates the number of days between the target date and today.
23+ *
24+ * @param {Date } targetDate - The date to compare with today.
25+ * @returns {number } The number of days between the target date and today.
26+ */
27+ function daysAgo ( targetDate ) {
28+ return ago ( targetDate , UNIT_DAY ) ;
29+ }
30+
31+ /**
32+ * Calculates the number of weeks between the target date and today.
33+ *
34+ * @param {Date } targetDate - The date to compare with today.
35+ * @returns {number } The number of weeks between the target date and today.
36+ */
37+ function weeksAgo ( targetDate ) {
38+ return ago ( targetDate , UNIT_WEEK ) ;
39+ }
40+
41+ /**
42+ * Calculates the number of months between the target date and today.
43+ *
44+ * @param {Date } targetDate - The date to compare with today.
45+ * @returns {number } The number of months between the target date and today.
46+ */
47+ function monthsAgo ( targetDate ) {
48+ return ago ( targetDate , UNIT_MONTH ) ;
49+ }
50+
51+ /**
52+ * Converts the target date into a human-readable string representing the time difference from today.
53+ *
54+ * @param {Date } targetDate - The date to convert.
55+ * @returns {string } A human-readable string representing the time difference from today.
56+ */
57+ function humanReadableDate ( targetDate ) {
58+ if ( daysAgo ( targetDate ) < 1 ) {
59+ return `today` ;
60+ } if ( daysAgo ( targetDate ) < 2 ) {
61+ return `yesterday` ;
62+ } else if ( daysAgo ( targetDate ) < 30 ) {
63+ return `${ daysAgo ( targetDate ) } days ago` ;
64+ } else if ( weeksAgo ( targetDate ) < 10 ) {
65+ return `${ weeksAgo ( targetDate ) } weeks ago` ;
66+ } else if ( monthsAgo ( targetDate ) < 10 ) {
67+ return `${ monthsAgo ( targetDate ) } months ago` ;
68+ } else {
69+ return targetDate . toISOString ( ) . split ( 'T' ) [ 0 ] ;
70+ }
71+ }
72+
73+ /**
74+ * Converts a Date object to an ISO 8601 formatted date string (YYYY-MM-DD).
75+ *
76+ * @param {Date } date - The date to be converted.
77+ * @returns {string } The ISO 8601 formatted date string.
78+ */
79+ function isoDate ( date ) {
80+ return date . toISOString ( ) . split ( 'T' ) [ 0 ] ;
81+ }
0 commit comments