Skip to content

Commit 788e069

Browse files
molovoRX14
authored andcommitted
Fix 12hr time formatting (#4988)
Currently, the time formatting directives `%I` and `%l` return `0` (zero) for midnight/midday, yet in most locales `12` would be preferred. This PR adds a simple ternary check to return `12` when `time.hour % 12` resolves as zero.
1 parent 88da972 commit 788e069

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

spec/std/time/time_spec.cr

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,7 @@ describe Time do
275275
it "formats" do
276276
t = Time.new 2014, 1, 2, 3, 4, 5, 6
277277
t2 = Time.new 2014, 1, 2, 15, 4, 5, 6
278+
t3 = Time.new 2014, 1, 2, 12, 4, 5, 6
278279

279280
t.to_s("%Y").should eq("2014")
280281
Time.new(1, 1, 2, 3, 4, 5, 6).to_s("%Y").should eq("0001")
@@ -304,9 +305,11 @@ describe Time do
304305

305306
t.to_s("%I").should eq("03")
306307
t2.to_s("%I").should eq("03")
308+
t3.to_s("%I").should eq("12")
307309

308310
t.to_s("%l").should eq(" 3")
309311
t2.to_s("%l").should eq(" 3")
312+
t3.to_s("%l").should eq("12")
310313

311314
# Note: we purposely match %p to am/pm and %P to AM/PM (makes more sense)
312315
t.to_s("%p").should eq("am")

src/time/format/formatter.cr

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,11 +92,13 @@ struct Time::Format
9292
end
9393

9494
def hour_12_zero_padded
95-
pad2 (time.hour % 12), '0'
95+
h = (time.hour % 12)
96+
pad2 (h == 0 ? 12 : h), '0'
9697
end
9798

9899
def hour_12_blank_padded
99-
pad2 (time.hour % 12), ' '
100+
h = (time.hour % 12)
101+
pad2 (h == 0 ? 12 : h), ' '
100102
end
101103

102104
def minute

0 commit comments

Comments
 (0)