Skip to content

Commit

Permalink
implement %o to get the day of the month as an ordinal
Browse files Browse the repository at this point in the history
  • Loading branch information
samsonjs committed May 15, 2013
1 parent e02de27 commit 088600d
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ e.g. `%q` becomes `q`. Use `%%` to get a literal `%` sign.
- M: the minute, padded to 2 digits (00-59)
- m: the month, padded to 2 digits (01-12)
- n: newline character
- o: day of the month as an ordinal (without padding), e.g. 1st, 2nd, 3rd, 4th, ...
- P: "am" or "pm" in lowercase [Ruby extension]
- p: "AM" or "PM"
- R: equivalent to `%H:%M`
Expand Down
16 changes: 16 additions & 0 deletions strftime.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@
case 'M': return pad(d.getMinutes(), padding);
case 'm': return pad(d.getMonth() + 1, padding);
case 'n': return '\n';
case 'o': return String(d.getDate()) + ordinal(d.getDate());
case 'P': return d.getHours() < 12 ? locale.am : locale.pm;
case 'p': return d.getHours() < 12 ? locale.AM : locale.PM;
case 'R': return _strftime(locale.formats.R || '%H:%M', d, locale);
Expand Down Expand Up @@ -204,6 +205,21 @@
return hour;
}

// Get the ordinal suffix for a number: st, nd, rd, or th
function ordinal(n) {
var i = n % 10
, ii = n % 100
;
if ((ii >= 11 && ii <= 13) || i === 0 || i >= 4) {
return 'th';
}
switch (i) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
}
}

// firstWeekday: 'sunday' or 'monday', default is 'sunday'
//
// Pilfered & ported from Ruby's strftime implementation.
Expand Down
1 change: 1 addition & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ assert.format('%0l', null, '06')
assert.format('%M', null, '51')
assert.format('%m', '06')
assert.format('%n', '\n')
assert.format('%o', '7th')
assert.format('%P', null, 'pm')
assert.format('%p', null, 'PM')
assert.format('%R', null, '18:51')
Expand Down

0 comments on commit 088600d

Please sign in to comment.