Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

implement week numbers: %U and %W, closes #16

  • Loading branch information...
commit 551bf4b5ad710b61c5b519767be86e395acdab21 1 parent 5db99ee
@samsonjs authored
Showing with 32 additions and 3 deletions.
  1. +24 −0 lib/index.js
  2. +8 −3 test/test.js
View
24 lib/index.js
@@ -108,10 +108,12 @@
case 's': return Math.floor((d.getTime() - msDelta) / 1000);
case 'T': return _strftime(locale.formats.T || '%H:%M:%S', d, locale);
case 't': return '\t';
+ case 'U': return pad(weekNumber(d, 'sunday'));
case 'u':
var day = d.getDay();
return day == 0 ? 7 : day; // 1 - 7, Monday is first day of the week
case 'v': return _strftime(locale.formats.v || '%e-%b-%Y', d, locale);
+ case 'W': return pad(weekNumber(d, 'monday'));
case 'w': return d.getDay(); // 0 - 6, Sunday is first day of the week
case 'Y': return d.getFullYear();
case 'y':
@@ -163,4 +165,26 @@
return hour;
}
+ // firstWeekday: 'sunday' or 'monday', default is 'sunday'
+ //
+ // Pilfered & ported from Ruby's strftime implementation.
+ function weekNumber(d, firstWeekday) {
+ firstWeekday = firstWeekday || 'sunday';
+
+ // This works by shifting the weekday back by one day if we
+ // are treating Monday as the first day of the week.
+ var wday = d.getDay();
+ if (firstWeekday == 'monday') {
+ if (wday == 0) // Sunday
+ wday = 6;
+ else
+ wday--;
+ }
+ var firstDayOfYear = new Date(d.getFullYear(), 0, 1)
+ , yday = (d - firstDayOfYear) / 86400000
+ , weekNum = (yday + 7 - wday) / 7
+ ;
+ return Math.floor(weekNum);
+ }
+
}());
View
11 test/test.js
@@ -15,12 +15,13 @@ assert.fn = function(value, msg) {
assert.equal('function', typeof value, msg)
}
-assert.format = function(format, expected, expectedUTC) {
+assert.format = function(format, expected, expectedUTC, time) {
+ time = time || Time
function _assertFmt(expected, name) {
name = name || 'strftime'
- var actual = lib[name](format, Time)
+ var actual = lib[name](format, time)
assert.equal(expected, actual,
- name + '("' + format + '", Time) is ' + JSON.stringify(actual)
+ name + '("' + format + '", ' + time + ') is ' + JSON.stringify(actual)
+ ', expected ' + JSON.stringify(expected))
}
@@ -64,8 +65,12 @@ assert.format('%s', '1307472705')
assert.format('%T', null, '18:51:45')
assert.format('%t', '\t')
assert.format('%u', '2')
+assert.format('%U', '23')
+assert.format('%U', '24', null, new Date(+Time + 5 * 86400000))
assert.format('%v', '7-Jun-2011')
assert.format('%w', '2')
+assert.format('%W', '23')
+assert.format('%W', '23', null, new Date(+Time + 5 * 86400000))
assert.format('%Y', '2011')
assert.format('%y', '11')
assert.format('%Z', null, 'GMT')

2 comments on commit 551bf4b

@yangchenyun

Wow, thanks for this quick fix!!

@samsonjs
Owner

I aim to please :)

Please sign in to comment.
Something went wrong with that request. Please try again.