commit 1ddfed2ab9f523e07cefd87f81aea325bf3fff3f
parent a447702df1d542aa2404dfad70a2d3c331a7cd46
Author: Chris Bracken <chris@bracken.jp>
Date: Sat, 21 Feb 2026 00:30:35 +0900
format: consolidate time printing functions
Diffstat:
| M | src/format.c | | | 53 | ++++++++++++++++++++--------------------------------- |
1 file changed, 20 insertions(+), 33 deletions(-)
diff --git a/src/format.c b/src/format.c
@@ -13,65 +13,52 @@ static bool is_unicode_modifier(wchar_t wc) {
return wc == 0x200D || (wc >= 0xFE00 && wc <= 0xFE0F);
}
-void print_time(FILE* out, time_t time, int timezone_offset) {
+static bool print_time_formatted(FILE* out,
+ time_t time,
+ int timezone_offset,
+ const char* format) {
assert(out != NULL);
+ assert(format != NULL);
// Reject any offset > 24 hours.
if (timezone_offset < -1440 || timezone_offset > 1440) {
warnx("invalid timezone offset: %d", timezone_offset);
- return;
+ return false;
}
time_t local_time = time + (timezone_offset * 60);
struct tm tm_buf;
struct tm* time_in = gmtime_r(&local_time, &tm_buf);
if (!time_in) {
- return;
+ return false;
}
char formatted_time[32];
- if (!strftime(formatted_time, sizeof(formatted_time), "%a, %e %b %Y %H:%M:%S",
- time_in)) {
+ if (!strftime(formatted_time, sizeof(formatted_time), format, time_in)) {
err(1, "strftime");
}
+ fprintf(out, "%s", formatted_time);
+ return true;
+}
+
+void print_time(FILE* out, time_t time, int timezone_offset) {
+ if (!print_time_formatted(out, time, timezone_offset,
+ "%a, %e %b %Y %H:%M:%S")) {
+ return;
+ }
char timezone_sign = timezone_offset < 0 ? '-' : '+';
int abs_offset = abs(timezone_offset);
int timezone_hours = abs_offset / 60;
int timezone_mins = abs_offset % 60;
- fprintf(out, "%s %c%02d%02d", formatted_time, timezone_sign, timezone_hours,
- timezone_mins);
+ fprintf(out, " %c%02d%02d", timezone_sign, timezone_hours, timezone_mins);
}
void print_time_z(FILE* out, time_t time) {
- assert(out != NULL);
- struct tm tm_buf;
- struct tm* time_in = gmtime_r(&time, &tm_buf);
- if (!time_in) {
- return;
- }
-
- char formatted_time[32];
- if (!strftime(formatted_time, sizeof(formatted_time), "%Y-%m-%dT%H:%M:%SZ",
- time_in)) {
- err(1, "strftime");
- }
- fprintf(out, "%s", formatted_time);
+ print_time_formatted(out, time, 0, "%Y-%m-%dT%H:%M:%SZ");
}
/* TODO: add timezone_offset to print_time_short. */
void print_time_short(FILE* out, time_t time) {
- assert(out != NULL);
- struct tm tm_buf;
- struct tm* time_in = gmtime_r(&time, &tm_buf);
- if (!time_in) {
- return;
- }
-
- char formatted_time[32];
- if (!strftime(formatted_time, sizeof(formatted_time), "%Y-%m-%d %H:%M",
- time_in)) {
- err(1, "strftime");
- }
- fprintf(out, "%s", formatted_time);
+ print_time_formatted(out, time, 0, "%Y-%m-%d %H:%M");
}
void print_percent_encoded(FILE* out, const char* str) {