File size: 2,321 Bytes
ccb6afe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from datetime import date as dt_date, timedelta


class Date:
    def __init__(self, *args):
        if len(args) == 0:
            self._date = dt_date.today()
        elif len(args) == 1:
            s = args[0]
            if isinstance(s, str):
                if 'T' in s:
                    date_part = s.split('T')[0]
                else:
                    date_part = s
                self._date = dt_date.fromisoformat(date_part)
            else:
                raise TypeError("Invalid argument type. Expected string.")
        elif len(args) == 3:
            year, month, day = args
            self._date = dt_date(year, month, day)
        else:
            raise TypeError("Date() requires 0, 1, or 3 arguments")

    def __eq__(self, other):
        if isinstance(other, Date):
            return self._date == other._date
        return False

    def __add__(self, days):
        if isinstance(days, int):
            new_date = self._date + timedelta(days=days)
            return Date(new_date.year, new_date.month, new_date.day)
        else:
            return NotImplemented

    __radd__ = __add__

    def __repr__(self):
        return f"Date({self._date.year}, {self._date.month}, {self._date.day})"

    def __str__(self):
        return f"{self._date.year:04}-{self._date.month:02}-{self._date.day:02}"

    # 小于
    def __lt__(self, other):
        if isinstance(other, Date):
            return self._date < other._date
        return False

    # 小于等于
    def __le__(self, other):
        if isinstance(other, Date):
            return self._date <= other._date
        return False

    # 大于
    def __gt__(self, other):
        if isinstance(other, Date):
            return self._date > other._date
        return False

    # 大于等于
    def __ge__(self, other):
        if isinstance(other, Date):
            return self._date >= other._date
        return False


if __name__ == "__main__":
    date1 = Date()  # 返回今天日期
    date2 = Date("2025-01-28")
    date3 = Date(2025, 1, 28)
    date4 = Date("2025-01-31T13:33:38.548Z")  # 删除所有时间信息,仅保留日期
    print(date2 == date3)  # True

    date4 = Date("2025-01-29")
    print(date2 + 1 == date4)

    print(date1, date2, date3, date4)

    print(date1 < date2)  # False