-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
date.dart
283 lines (230 loc) · 8.63 KB
/
date.dart
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import 'dart:core';
import 'dart:core' as core;
import 'package:clock/clock.dart';
import 'package:dartx/dartx.dart';
import 'package:meta/meta.dart';
import 'package:oxidized/oxidized.dart';
import '../date_time/date_time.dart';
import '../parser.dart';
import '../time/time.dart';
import '../utils.dart';
import 'duration.dart';
import 'month/month.dart';
import 'month/month_day.dart';
import 'month/year_month.dart';
import 'ordinal_date.dart';
import 'week/week_date.dart';
import 'week/year_week.dart';
import 'weekday.dart';
import 'year.dart';
/// A date in the ISO 8601 calendar.
///
/// The date is represented by a [YearMonth] (= [Year] + [Month]) and a [day]
/// of the month.
///
/// See also:
///
/// - [WeekDate], which represents a date by a [YearWeek] and a [Weekday].
/// - [OrdinalDate], which represents a date by a [Year] and a day of the year.
@immutable
final class Date
with ComparisonOperatorsFromComparable<Date>
implements Comparable<Date> {
static Result<Date, String> from(
Year year, [
Month month = Month.january,
int day = 1,
]) =>
fromYearMonthAndDay(YearMonth(year, month), day);
static Result<Date, String> fromYearMonthAndDay(
YearMonth yearMonth,
int day,
) {
if (day < 1 || day > yearMonth.length.inDays) {
return Err('Invalid day for $yearMonth: $day');
}
return Ok(Date._(yearMonth, day));
}
static Result<Date, String> fromYearAndMonthDay(
Year year,
MonthDay monthDay,
) =>
from(year, monthDay.month, monthDay.day);
const Date._(this.yearMonth, this.day);
/// The UNIX epoch: 1970-01-01.
///
/// https://en.wikipedia.org/wiki/Unix_time
static const unixEpoch = Date._(YearMonth(Year(1970), Month.january), 1);
/// The date corresponding to the given number of days since the [unixEpoch].
factory Date.fromDaysSinceUnixEpoch(Days sinceUnixEpoch) {
// https://howardhinnant.github.io/date_algorithms.html#civil_from_days
var daysSinceUnixEpoch = sinceUnixEpoch.inDays;
daysSinceUnixEpoch += 719468;
final era = (daysSinceUnixEpoch >= 0
? daysSinceUnixEpoch
: daysSinceUnixEpoch - 146096) ~/
146097;
final dayOfEra = daysSinceUnixEpoch % 146097;
assert(0 <= dayOfEra && dayOfEra <= 146096);
final yearOfEra = (dayOfEra -
dayOfEra ~/ 1460 +
dayOfEra ~/ 36524 -
dayOfEra ~/ 146096) ~/
365;
assert(0 <= yearOfEra && yearOfEra <= 399);
final shiftedYear = yearOfEra + era * 400;
final dayOfYear =
dayOfEra - (yearOfEra * 365 + yearOfEra ~/ 4 - yearOfEra ~/ 100);
assert(0 <= dayOfYear && dayOfYear <= 365);
final shiftedMonth = (dayOfYear * 5 + 2) ~/ 153;
assert(0 <= shiftedMonth && shiftedMonth <= 11);
final day = dayOfYear - (shiftedMonth * 153 + 2) ~/ 5 + 1;
assert(1 <= day && day <= 31);
final (year, month) = shiftedMonth < 10
? (shiftedYear, shiftedMonth + 3)
: (shiftedYear + 1, shiftedMonth - 9);
assert(1 <= month && month <= 12);
return Date._(
YearMonth(Year(year), Month.fromNumber(month).unwrap()),
day,
);
}
factory Date.todayInLocalZone({Clock? clock}) =>
DateTime.nowInLocalZone(clock: clock).date;
factory Date.todayInUtc({Clock? clock}) =>
DateTime.nowInUtc(clock: clock).date;
factory Date.fromJson(String json) => unwrapParserResult(parse(json));
static Result<Date, FormatException> parse(String value) =>
Parser.parseDate(value);
final YearMonth yearMonth;
Year get year => yearMonth.year;
Month get month => yearMonth.month;
/// The one-based day of the month.
final int day;
/// The one-based day of the year.
int get dayOfYear {
// https://en.wikipedia.org/wiki/Ordinal_date#Zeller-like
final isJanuaryOrFebruary = this.month <= Month.february;
final month =
isJanuaryOrFebruary ? this.month.number + 12 : this.month.number;
final marchBased = (153 * ((month - 3) % 12) + 2) ~/ 5 + day;
return isJanuaryOrFebruary
? marchBased - 306
: marchBased + 59 + (year.isLeapYear ? 1 : 0);
}
MonthDay get monthDay => MonthDay.from(month, day).unwrap();
/// This date, represented as an [OrdinalDate].
OrdinalDate get asOrdinalDate => OrdinalDate.from(year, dayOfYear).unwrap();
YearWeek get yearWeek {
// Algorithm from https://en.wikipedia.org/wiki/ISO_week_date#Algorithms
final weekOfYear = (dayOfYear - weekday.number + 10) ~/ 7;
return switch (weekOfYear) {
0 => year.previous.lastWeek,
53 when year.numberOfWeeks == 52 => year.next.firstWeek,
_ => YearWeek.from(year, weekOfYear).unwrap()
};
}
Weekday get weekday =>
Weekday.fromNumber((daysSinceUnixEpoch.inDays + 3) % 7 + 1).unwrap();
/// This date, represented as a [WeekDate].
WeekDate get asWeekDate => WeekDate(yearWeek, weekday);
/// The number of days since the [unixEpoch].
Days get daysSinceUnixEpoch {
// https://howardhinnant.github.io/date_algorithms.html#days_from_civil
final (year, month) = this.month <= Month.february
? (this.year.number - 1, this.month.number + 9)
: (this.year.number, this.month.number - 3);
final era = (year >= 0 ? year : year - 399) ~/ 400;
final yearOfEra = year - era * 400;
assert(0 <= yearOfEra && yearOfEra <= 399);
final dayOfYear = (month * 153 + 2) ~/ 5 + day - 1;
assert(0 <= dayOfYear && dayOfYear <= 365);
final dayOfEra =
yearOfEra * 365 + yearOfEra ~/ 4 - yearOfEra ~/ 100 + dayOfYear;
assert(0 <= dayOfEra && dayOfEra <= 146096);
return Days(era * 146097 + dayOfEra - 719468);
}
bool isTodayInLocalZone({Clock? clock}) =>
this == Date.todayInLocalZone(clock: clock);
bool isTodayInUtc({Clock? clock}) => this == Date.todayInUtc(clock: clock);
/// A [DateTime] combining this [Date] and the given [time].
DateTime at(Time time) => DateTime(this, time);
/// A [DateTime] at [Time.midnight] on this date.
DateTime get atMidnight => at(Time.midnight);
/// A [DateTime] at [Time.noon] on this date.
DateTime get atNoon => at(Time.noon);
/// Adds the given [duration] to this date.
///
/// The calculation is done as follows:
///
/// 1. Add the months of the duration. If the day of the month is greater than
/// the number of days in the resulting month, set it to the last day of
/// that month.
/// 2. Add the days of the duration, potentially updating the year and month
/// again.
///
/// Examples:
///
/// - 2023-03-31 + 1 month = 2023-04-30, since April only has 30 days.
/// - 2023-03-31 + 1 month and 1 day = 2023-05-01
Date operator +(DaysDuration duration) {
final CompoundDaysDuration(:months, :days) =
duration.asCompoundDaysDuration;
final yearMonthWithMonths = yearMonth + months;
final dateWithMonths = Date._(
yearMonthWithMonths,
day.coerceAtMost(yearMonthWithMonths.length.inDays),
);
return days.inDays == 0
? dateWithMonths
: Date.fromDaysSinceUnixEpoch(dateWithMonths.daysSinceUnixEpoch + days);
}
Date operator -(DaysDuration duration) => this + (-duration);
/// The date after this one.
Date get next => this + const Days(1);
/// The date before this one.
Date get previous => this - const Days(1);
/// Returns `this - other` as a number of [Days].
Days difference(Date other) => daysSinceUnixEpoch - other.daysSinceUnixEpoch;
/// The next-closest date with the given [weekday].
///
/// If this date already falls on the given [weekday], it is returned.
Date nextOrSame(Weekday weekday) =>
this + this.weekday.untilNextOrSame(weekday);
/// The next-closest previous date with the given [weekday].
///
/// If this date already falls on the given [weekday], it is returned.
Date previousOrSame(Weekday weekday) =>
this + this.weekday.untilPreviousOrSame(weekday);
Result<Date, String> copyWith({
YearMonth? yearMonth,
Year? year,
Month? month,
int? day,
}) {
assert(yearMonth == null || (year == null && month == null));
return Date.fromYearMonthAndDay(
yearMonth ?? YearMonth(year ?? this.year, month ?? this.month),
day ?? this.day,
);
}
@override
int compareTo(Date other) {
final result = yearMonth.compareTo(other.yearMonth);
if (result != 0) return result;
return day.compareTo(other.day);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other is Date && yearMonth == other.yearMonth && day == other.day);
}
@override
int get hashCode => Object.hash(yearMonth, day);
@override
String toString() {
final day = this.day.toString().padLeft(2, '0');
return '$yearMonth-$day';
}
String toJson() => toString();
}