Skip to content

Fix year padding in to_rfc3339 #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions src/gleam/time/timestamp.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -170,18 +170,23 @@ pub fn to_rfc3339(timestamp: Timestamp, offset_minutes offset: Int) -> String {
let offset_minutes = modulo(offset, 60)
let offset_hours = int.absolute_value(floored_div(offset, 60.0))

let n = fn(n) { int.to_string(n) |> string.pad_start(2, "0") }
let n2 = pad_digit(_, to: 2)
let n4 = pad_digit(_, to: 4)
let out = ""
let out = out <> n(years) <> "-" <> n(months) <> "-" <> n(days)
let out = out <> n4(years) <> "-" <> n2(months) <> "-" <> n2(days)
let out = out <> "T"
let out = out <> n(hours) <> ":" <> n(minutes) <> ":" <> n(seconds)
let out = out <> n2(hours) <> ":" <> n2(minutes) <> ":" <> n2(seconds)
case int.compare(offset, 0) {
order.Eq -> out <> "Z"
order.Gt -> out <> "+" <> n(offset_hours) <> ":" <> n(offset_minutes)
order.Lt -> out <> "-" <> n(offset_hours) <> ":" <> n(offset_minutes)
order.Gt -> out <> "+" <> n2(offset_hours) <> ":" <> n2(offset_minutes)
order.Lt -> out <> "-" <> n2(offset_hours) <> ":" <> n2(offset_minutes)
}
}

fn pad_digit(digit: Int, to desired_length: Int) -> String {
int.to_string(digit) |> string.pad_start(desired_length, "0")
}

fn modulo(n: Int, m: Int) -> Int {
case int.modulo(n, m) {
Ok(n) -> n
Expand Down
24 changes: 24 additions & 0 deletions test/gleam/time/timestamp_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -207,3 +207,27 @@ pub fn to_rfc3339_8_test() {
|> timestamp.to_rfc3339(-120)
|> should.equal("1970-01-01T02:00:00-02:00")
}

pub fn to_rfc3339_9_test() {
timestamp.from_unix_seconds(-62_167_219_200)
|> timestamp.to_rfc3339(0)
|> should.equal("0000-01-01T00:00:00Z")
}

pub fn to_rfc3339_10_test() {
timestamp.from_unix_seconds(-62_135_596_800)
|> timestamp.to_rfc3339(0)
|> should.equal("0001-01-01T00:00:00Z")
}

pub fn to_rfc3339_11_test() {
timestamp.from_unix_seconds(-61_851_600_000)
|> timestamp.to_rfc3339(0)
|> should.equal("0010-01-01T00:00:00Z")
}

pub fn to_rfc3339_12_test() {
timestamp.from_unix_seconds(-59_011_459_200)
|> timestamp.to_rfc3339(0)
|> should.equal("0100-01-01T00:00:00Z")
}
Loading