最后活跃于 1 year ago

evert's Avatar evert 修订了这个 Gist 1 year ago. 转到此修订

1 file changed, 52 insertions

date-diff.ts(文件已创建)

@@ -0,0 +1,52 @@
1 + const calcDateDifference = (
2 + start: string | Date,
3 + end: string | Date,
4 + ): { year: number; month: number; day: number } => {
5 + // Convert to true dates without time
6 + let startDate = new Date(new Date(start).toISOString().substring(0, 10));
7 + let endDate = new Date(
8 + (end ? new Date(end) : new Date()).toISOString().substring(0, 10),
9 + );
10 +
11 + // If start date comes after end, flip them around
12 + if (startDate > endDate) {
13 + const swap = startDate;
14 + startDate = endDate;
15 + endDate = swap;
16 + }
17 +
18 + // Account for leap years
19 + const startYear = startDate.getFullYear();
20 + const february =
21 + (startYear % 4 === 0 && startYear % 100 !== 0) || startYear % 400 === 0
22 + ? 29
23 + : 28;
24 + const daysInMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
25 +
26 + // Create year and month diffs
27 + let yearDiff = endDate.getFullYear() - startYear;
28 + let monthDiff = endDate.getMonth() - startDate.getMonth();
29 + if (monthDiff < 0) {
30 + yearDiff--;
31 + monthDiff += 12;
32 + }
33 +
34 + // Create day diff while adjusting others
35 + let dayDiff = endDate.getDate() - startDate.getDate();
36 + if (dayDiff < 0) {
37 + if (monthDiff > 0) {
38 + monthDiff--;
39 + } else {
40 + yearDiff--;
41 + monthDiff = 11;
42 + }
43 + dayDiff += daysInMonth[startDate.getMonth()];
44 + }
45 +
46 + // Return true differentials
47 + return {
48 + year: yearDiff,
49 + month: monthDiff,
50 + day: dayDiff,
51 + };
52 + }
上一页 下一页