leroycep / zig-tzif

TZif parsing for Zig
MIT License
8 stars 2 forks source link

Efficiency of epoch time calculations #9

Closed FObersteiner closed 11 months ago

FObersteiner commented 11 months ago

https://github.com/leroycep/zig-tzif/blob/3cc489a81777dd217cd5bb81629128bbdd6b85a2/tzif.zig#L538

addressing your comment, I think to make this more efficient, we could use days as base period, then add / subtract seconds where needed.

What I'm referring to here is Howard Hinnant's "date" algorithms - C++ library, explanations. For example the calculation of a transition time t from a given MonthWeekDay rule mwdand year could look like

// calculate unix time based on year and m/n/d from rule
// start with year-month, day = 1
t = @as(i64, unixdaysFromDate([3]u16{ year, mwd.m, 1 }));
// now find n'th weekday d
const first_wday = @mod((t + 4), 7);
var days_offset = mwd.d - first_wday; // days to add to reach first specified weekday in month
if (days_offset < 0) days_offset += 7;
var n = mwd.n;
if (mwd.n == 5 and days_offset + 28 >= days_in_month(mwd.m, std.time.epoch.isLeapYear(year))) n = 4;
t += (days_offset + 7 * (n - 1));
t *= std.time.s_per_day;
t += mwd.transition_time;
t -= offset; // correct for UTC offset *before* transition

unixdaysFromDate takes a triple year-month-day and returns days since the Unix epoch (Howard just calls it "days_from_civil"). zig-port. I've tested the applicability with an older version of your code, so the field names are different than in the current version etc. but... you get the point ;-)

leroycep commented 11 months ago

That is a very nice reference, thank you for linking it.

I'm thinking that keeping zig-tzif would make more sense as part of a datetime library than as a separate component that a datetime library uses.

Especially during testing, the need to manually convert dates into unix timestamps seems less than ideal. I would prefer it if the tests used ISO8601.

I'll probably revive zig-chrono and copy the code from zig-tzif into it. I also wouldn't mind contributing to zdt. I do want to experiment with zig-chrono's API, because I feel there's a better design out there than the current one.

FObersteiner commented 11 months ago

Yes, that is a good point. A time zone library makes much more sense in combination with a datetime library. That's why I came here in the first place.

As for zdt, I'm a bit unsure at the moment where this could go. I started it as an exploratory project, but I can see it becoming something useful - if it includes time zone handling. The basics are working at the moment but I have some major changes in mind. I'll keep you posted - your contribution would be very much appreciated :) I also want to have a look at zig-chrono and Rust's chrono. I never got that deep into Rust but let's see.