Skip to content

Commit

Permalink
Fix incorrect to_gmt_offset result
Browse files Browse the repository at this point in the history
  • Loading branch information
hkalexling authored and lerno committed Sep 28, 2024
1 parent 8a0b0f5 commit fe9e434
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/std/time/datetime.c3
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ fn TzDateTime DateTime.to_gmt_offset(self, int gmt_offset)
* @ensure self.time == return.time
**/
fn TzDateTime TzDateTime.to_gmt_offset(self, int gmt_offset) {
Time time = self.time + (Time)(gmt_offset - self.gmt_offset) * (Time)time::SEC;
if (self.gmt_offset == gmt_offset) return self;
Time time = self.time + (Time)gmt_offset * (Time)time::SEC;
DateTime dt = from_time(time);
dt.time = self.time;
return { dt, gmt_offset };
Expand Down
21 changes: 21 additions & 0 deletions test/unit/stdlib/time/datetime.c3
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ fn void test_timezone()
int offset_hours = 7;
int offset = offset_hours * 3600;

int target_offset_hours = -4;
int target_offset = target_offset_hours * 3600;

DateTime d1 = datetime::from_date(2022, OCTOBER, 15);
TzDateTime d2 = datetime::from_date_tz(2022, OCTOBER, 15, gmt_offset: offset);

Expand Down Expand Up @@ -127,4 +130,22 @@ fn void test_timezone()
assert(tz.day == 15);
assert(tz.hour == 0);
assert(tz.gmt_offset == offset);

// Conversion from GMT+7 to GMT-4
tz = d2.to_gmt_offset(target_offset);
assert(tz.year == d2.year);
assert(tz.month == d2.month);
assert(tz.day == d2.day - 1);
assert(tz.hour == 24 - (offset_hours - target_offset_hours));
assert(tz.time == t2);
assert(tz.gmt_offset == target_offset);

// Conversion with the same offset
tz = d2.to_gmt_offset(offset);
assert(tz.year == d2.year);
assert(tz.month == d2.month);
assert(tz.day == d2.day);
assert(tz.hour == d2.hour);
assert(tz.time == t2);
assert(tz.gmt_offset == offset);
}

0 comments on commit fe9e434

Please sign in to comment.