Skip to content

Commit

Permalink
Fix 12hr time formatting (#4988)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
molovo authored and RX14 committed Sep 21, 2017
1 parent 88da972 commit 788e069
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
3 changes: 3 additions & 0 deletions spec/std/time/time_spec.cr
Expand Up @@ -275,6 +275,7 @@ describe Time do
it "formats" do
t = Time.new 2014, 1, 2, 3, 4, 5, 6
t2 = Time.new 2014, 1, 2, 15, 4, 5, 6
t3 = Time.new 2014, 1, 2, 12, 4, 5, 6

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

t.to_s("%I").should eq("03")
t2.to_s("%I").should eq("03")
t3.to_s("%I").should eq("12")

t.to_s("%l").should eq(" 3")
t2.to_s("%l").should eq(" 3")
t3.to_s("%l").should eq("12")

# Note: we purposely match %p to am/pm and %P to AM/PM (makes more sense)
t.to_s("%p").should eq("am")
Expand Down
6 changes: 4 additions & 2 deletions src/time/format/formatter.cr
Expand Up @@ -92,11 +92,13 @@ struct Time::Format
end

def hour_12_zero_padded
pad2 (time.hour % 12), '0'
h = (time.hour % 12)
pad2 (h == 0 ? 12 : h), '0'
end

def hour_12_blank_padded
pad2 (time.hour % 12), ' '
h = (time.hour % 12)
pad2 (h == 0 ? 12 : h), ' '
end

def minute
Expand Down

0 comments on commit 788e069

Please sign in to comment.