Debian Codegraph @

time/date/format.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use fmt;
5 use io;
6 use memio;
7 use strings;
8 use time;
9
10 // [[format]] layout for the email date format.
11 export def EMAIL: str = "%a, %d %b %Y %H:%M:%S %z";
12
13 // [[format]] layout for the email date format, with zone offset and
14 // zone abbreviation.
15 export def EMAILZONE: str = "%a, %d %b %Y %H:%M:%S %z %Z";
16
17 // [[format]] layout for the POSIX locale's default date & time representation.
18 export def POSIX: str = "%a %b %e %H:%M:%S %Y";
19
20 // [[format]] layout compatible with RFC 3339.
21 export def RFC3339: str = "%Y-%m-%dT%H:%M:%S%z";
22
23 // [[format]] layout for a standard, collatable timestamp.
24 export def STAMP: str = "%Y-%m-%d %H:%M:%S";
25
26 // [[format]] layout for a standard, collatable timestamp with nanoseconds.
27 export def STAMPNANO: str = "%Y-%m-%d %H:%M:%S.%N";
28
29 // [[format]] layout for a standard, collatable timestamp with nanoseconds
30 // and zone offset.
31 export def STAMPZOFF: str = "%Y-%m-%d %H:%M:%S.%N %z";
32
33 // [[format]] layout for a standard, collatable timestamp with nanoseconds,
34 // zone offset, and zone abbreviation.
35 export def STAMPZONE: str = "%Y-%m-%d %H:%M:%S.%N %z %Z";
36
37 // [[format]] layout for a standard, collatable timestamp with nanoseconds,
38 // zone offset, zone abbreviation, and locality.
39 export def STAMPLOC: str = "%Y-%m-%d %H:%M:%S.%N %z %Z %L";
40
41 // [[format]] layout for an ISO week-numbering timestamp.
42 export def ISOWKSTAMP: str = "%G-W%V-%u %H:%M:%S";
43
44 // [[format]] layout for a friendly, comprehensive datetime.
45 export def JOURNAL: str = "%Y %b %d, %a %H:%M:%S %z %Z %L";
46
47 // [[format]] layout for a friendly, terse datetime.
48 export def WRIST: str = "%b-%d %a %H:%M %Z";
49
50 // [[format]] layout for a precise timescalar second and nanosecond.
51 export def QUARTZ: str = "%s.%N";
52
53 // [[format]] layout for a precise timescalar second, nanosecond,
54 // and zone offset.
55 export def QUARTZZOFF: str = "%s.%N%z";
56
57 // [[format]] layout for a precise timescalar second, nanosecond,
58 // and locality.
59 export def QUARTZLOC: str = "%s.%N:%L";
60
61 // TODO: consider adding specifier for timescale name, and "QUARTZTSC" layout.
62 // e.g. "%s.%N!%C" -> 123456789123.000000000!UTC
63
64 def WEEKDAYS: [_]str = [
65 "Monday",
66 "Tuesday",
67 "Wednesday",
68 "Thursday",
69 "Friday",
70 "Saturday",
71 "Sunday",
72 ];
73
74 def WEEKDAYS_SHORT: [_]str = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
75
76 def MONTHS: [_]str = [
77 "January",
78 "February",
79 "March",
80 "April",
81 "May",
82 "June",
83 "July",
84 "August",
85 "September",
86 "October",
87 "November",
88 "December",
89 ];
90
91 def MONTHS_SHORT: [_]str = [
92 "Jan", "Feb", "Mar",
93 "Apr", "May", "Jun",
94 "Jul", "Aug", "Sep",
95 "Oct", "Nov", "Dec",
96 ];
97
98 // Formats a [[date]] and writes it into a caller supplied buffer. The returned
99 // string is borrowed from this buffer. If the resulting string does not fit
100 // into 'buf', nomem is returned.
101 export fn bsformat(buf: []u8, layout: str, d: *date) (str | nomem) = {
102 let sink = memio::fixed(buf);
103 match (format(&sink, layout, d)) {
104 case size => void;
105 case nomem =>
106 return nomem;
107 case =>
108 abort();
109 };
110 return memio::string(&sink)!;
111 };
112
113 // Formats a [[date]] and writes it into a heap-allocated string.
114 // The caller must free the return value.
115 export fn asformat(layout: str, d: *date) (str | nomem) = {
116 let sink = memio::dynamic();
117 match (format(&sink, layout, d)) {
118 case size => void;
119 case nomem =>
120 io::close(&sink)!;
121 return nomem;
122 case =>
123 abort();
124 };
125 return memio::string(&sink)!;
126 };
127
128 // Formats a [[date]] according to a layout and writes to an [[io::handle]].
129 //
130 // The layout may contain any of the following format specifiers listed below.
131 // These specifiers emit 2 digit zero-padded decimals unless stated otherwise.
132 // Use of unimplemented specifiers or an invalid layout will cause an abort.
133 //
134 // - %% : A single literal '%' character.
135 // - %a : The day of the week, abbreviated name. ("Sun").
136 // - %A : The day of the week, full name. ("Sunday").
137 // - %b : The month, abbreviated name. ("Jan").
138 // - %B : The month, full name. ("January").
139 // - %C : The century (the year without the last 2 digits). ("20").
140 // - %d : The day of the month. Range 01 to 31. ("02").
141 // - %e : The day of the month. Range 1 to 31,
142 // right-aligned, space-padded. (" 2").
143 // - %F : The full Gregorian calendar date.
144 // Alias for "%Y-%m-%d". ("2000-01-02").
145 // - %G : The ISO week-numbering year. At least 4 digits.
146 // ISO-years before the Common Era have a minus sign prefix. ("1999").
147 // - %H : The hour of the day of a 24-hour clock. Range 00 to 23. ("15").
148 // - %I : The hour of the day of a 12-hour clock. Range 01 to 12. ("03").
149 // - %j : The ordinal day of the year. 3 digits, range 001 to 366. ("002").
150 // - %L : The locality's name (the timezone identifier). ("Europe/Amsterdam").
151 // - %m : The month of the year. Range 01 to 12. ("01").
152 // - %M : The minute of the hour. Range 00 to 59. ("04").
153 // - %N : The nanosecond of the second. 9 digits,
154 // range 000000000 to 999999999. ("600000000").
155 // - %p : The meridian indicator, either "AM" or "PM".
156 // "AM" includes midnight, and "PM" includes noon.
157 // - %s : The number of seconds since the locality's epoch. ("946821845").
158 // - %S : The second of the minute. Range 00 to 59. ("05").
159 // - %T : The wall-time of a 24-hour clock without nanoseconds.
160 // Alias for "%H:%M:%S". ("15:04:05").
161 // - %u : The day of the week. 1 digit, range 1 to 7, Monday to Sunday. ("7").
162 // - %U : The sunday-week of the year. Range 00 to 53.
163 // The year's first Sunday is the first day of week 01. ("01").
164 // - %V : The week of the ISO week-numbering year. Range 01 to 53. ("52").
165 // - %w : The day of the sunday-week.
166 // 1 digit, range 0 to 6, Sunday to Saturday. ("0").
167 // - %W : The week of the year. Range 00 to 53.
168 // The year's first Monday is the first day of week 01. ("00").
169 // - %y : The year's last 2 digits, no century digits. Range 00 to 99. ("00").
170 // - %Y : The year. At least 4 digits.
171 // Years before the Common Era have a minus sign prefix. ("2000").
172 // - %z : The observed zone offset. ("+0100").
173 // - %Z : The observed zone abbreviation. ("CET").
174 export fn format(h: io::handle, layout: str, d: *date) (size | io::error) = {
175 let iter = strings::iter(layout);
176 let z = 0z;
177 for (let r => strings::next(&iter)) {
178 if (r == '%') {
179 match (strings::next(&iter)) {
180 case let spec: rune =>
181 z += fmtspec(h, spec, d)?;
182 case done =>
183 abort("layout has dangling '%'");
184 };
185 } else {
186 z += memio::appendrune(h, r)?;
187 };
188 };
189 return z;
190 };
191
192 fn fmtspec(out: io::handle, r: rune, d: *date) (size | io::error) = {
193 switch (r) {
194 case 'a' =>
195 return fmt::fprint(out, WEEKDAYS_SHORT[_weekday(d)]);
196 case 'A' =>
197 return fmt::fprint(out, WEEKDAYS[_weekday(d)]);
198 case 'b' =>
199 return fmt::fprint(out, MONTHS_SHORT[_month(d) - 1]);
200 case 'B' =>
201 return fmt::fprint(out, MONTHS[_month(d) - 1]);
202 case 'C' =>
203 return fmt::fprintf(out, "{:.2}", _year(d) / 100);
204 case 'd' =>
205 return fmt::fprintf(out, "{:.2}", _day(d));
206 case 'e' =>
207 return fmt::fprintf(out, "{: 2}", _day(d));
208 case 'F' =>
209 return fmt::fprintf(out, "{:.4}-{:.2}-{:.2}",
210 _year(d), _month(d), _day(d));
211 case 'G' =>
212 return fmt::fprintf(out, "{:.4}", _isoweekyear(d));
213 case 'H' =>
214 return fmt::fprintf(out, "{:.2}", _hour(d));
215 case 'I' =>
216 return fmt::fprintf(out, "{:.2}", (_hour(d) + 11) % 12 + 1);
217 case 'j' =>
218 return fmt::fprintf(out, "{:.3}", _yearday(d));
219 case 'L' =>
220 return fmt::fprint(out, d.loc.name);
221 case 'm' =>
222 return fmt::fprintf(out, "{:.2}", _month(d));
223 case 'M' =>
224 return fmt::fprintf(out, "{:.2}", _minute(d));
225 case 'N' =>
226 return fmt::fprintf(out, "{:.9}", _nanosecond(d));
227 case 'p' =>
228 return fmt::fprint(out, if (_hour(d) < 12) "AM" else "PM");
229 case 's' =>
230 return fmt::fprintf(out, "{:.2}", d.sec);
231 case 'S' =>
232 return fmt::fprintf(out, "{:.2}", _second(d));
233 case 'T' =>
234 return fmt::fprintf(out, "{:.2}:{:.2}:{:.2}",
235 _hour(d), _minute(d), _second(d));
236 case 'u' =>
237 return fmt::fprintf(out, "{}", _weekday(d) + 1);
238 case 'U' =>
239 return fmt::fprintf(out, "{:.2}", _sundayweek(d));
240 case 'V' =>
241 return fmt::fprintf(out, "{:.2}", _isoweek(d));
242 case 'w' =>
243 return fmt::fprintf(out, "{}", (_weekday(d) + 1) % 7);
244 case 'W' =>
245 return fmt::fprintf(out, "{:.2}", _week(d));
246 case 'y' =>
247 return fmt::fprintf(out, "{:.2}", _year(d) % 100);
248 case 'Y' =>
249 return fmt::fprintf(out, "{:.4}", _year(d));
250 case 'z' =>
251 return fmtzoff(out, zone(d).zoff);
252 case 'Z' =>
253 return fmt::fprint(out, zone(d).abbr);
254 case '%' =>
255 return fmt::fprint(out, "%");
256 case =>
257 abort("layout has unrecognised specifier");
258 };
259 };
260
261 fn fmtzoff(h: io::handle, zoff: time::duration) (size | io::error) = {
262 // TODO: formatting & parsing: account for all possible styles for zoffs
263 // (+NN, +NNNN, +NN:NN, +NN:NN:NN, +NN:NN:NN.NNNNNNNNN).
264 const (sign, zo) =
265 if (zoff >= 0)
266 ('+', calc_hmsn(zoff))
267 else
268 ('-', calc_hmsn(-zoff));
269 const (hr, mi) = (zo.0, zo.1);
270 return fmt::fprintf(h, "{}{:.2}{:.2}", sign, hr, mi);
271 };
272
273 @test fn format() void = {
274 const d = new(UTC, 0, 1994, 1, 1, 2, 17, 5, 24)!;
275
276 const cases = [
277 // special characters
278 ("%%", "%"),
279 // hour
280 ("%H", "02"),
281 ("%I", "02"),
282 // minute
283 ("%M", "17"),
284 // second
285 ("%S", "05"),
286 // nanosecond
287 ("%N", "000000024"),
288 // am/pm
289 ("%p", "AM"),
290 // day
291 ("%d", "01"),
292 // day
293 ("%e", " 1"),
294 // month
295 ("%m", "01"),
296 // year
297 ("%Y", "1994"),
298 ("%y", "94"),
299 ("%C", "19"),
300 // month name
301 ("%b", "Jan"),
302 ("%B", "January"),
303 // weekday
304 ("%u", "6"),
305 ("%w", "6"),
306 ("%a", "Sat"),
307 ("%A", "Saturday"),
308 // yearday
309 ("%j", "001"),
310 // week
311 ("%W", "00"),
312 // full date
313 ("%F", "1994-01-01"),
314 // full time
315 ("%T", "02:17:05"),
316 // Unix timestamp
317 ("%s", "757390625"),
318 ];
319
320 for (let (layout, expected) .. cases) {
321 const actual = asformat(layout, &d)!;
322 defer free(actual);
323 if (actual != expected) {
324 fmt::printfln(
325 "expected format({}, &d) to be {} but was {}",
326 layout, expected, actual
327 )!;
328 abort();
329 };
330 };
331 };