diff --git a/README.md b/README.md index 0d4e59c..c379c37 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,11 @@ format(1000 * 60 * 60 * 24 - 1) // '23:59:59' // 365 days looks like this (not bothering with years) format(1000 * 60 * 60 * 24 * 365) // '365:00:00:00' +// with leading zeros formatting looks like this +format(1000 * 60, { leading: true }) // '01:00' +format(1000 * 60 - 1, { leading: true }) // '00:59' +format(1000 * 60 * 60, { leading: true }) // '01:00:00' + // *NEW negative support* anything under a second is rounded down to zero format(-999) // '0:00' diff --git a/index.js b/index.js index cc58a33..e0df70d 100644 --- a/index.js +++ b/index.js @@ -1,12 +1,13 @@ var parseMs = require('parse-ms') var addZero = require('add-zero') -module.exports = function (ms) { +module.exports = function (ms, options) { + var leading = options && options.leading var unsignedMs = ms < 0 ? -ms : ms var sign = ms <= -1000 ? '-' : '' var t = parseMs(unsignedMs) var seconds = addZero(t.seconds) if (t.days) return sign + t.days + ':' + addZero(t.hours) + ':' + addZero(t.minutes) + ':' + seconds - if (t.hours) return sign + t.hours + ':' + addZero(t.minutes) + ':' + seconds - return sign + t.minutes + ':' + seconds + if (t.hours) return sign + (leading ? addZero(t.hours) : t.hours) + ':' + addZero(t.minutes) + ':' + seconds + return sign + (leading ? addZero(t.minutes) : t.minutes) + ':' + seconds } diff --git a/test/index.js b/test/index.js index c9538e3..8ead7a2 100644 --- a/test/index.js +++ b/test/index.js @@ -33,6 +33,20 @@ test('it works with negative durations', function (t) { t.end() }) +test('it works with leading zeros', function (t) { + t.equal(f(999, { leading: true }), '00:00', 'anything under a second is 00:00') + t.equal(f(1000, { leading: true }), '00:01', 'check 1000 milliseconds is a second') + t.equal(f(1000 * 2 - 1, { leading: true }), '00:01', 'rounds 1999 down to 00:01') + t.equal(f(1000 * 60, { leading: true }), '01:00', 'check 60 seconds is a minute') + t.equal(f(1000 * 60 - 1, { leading: true }), '00:59', 'check 59 seconds looks ok') + t.equal(f(1000 * 60 * 60, { leading: true }), '01:00:00', 'check 60 minutes is an hour') + t.equal(f(1000 * 60 * 60 - 1, { leading: true }), '59:59', 'check 59 minutes looks ok') + t.equal(f(1000 * 60 * 60 * 24, { leading: true }), '1:00:00:00', 'check 24 hours is a day') + t.equal(f(1000 * 60 * 60 * 24 - 1, { leading: true }), '23:59:59', 'check 23 hours looks okay') + t.equal(f(1000 * 60 * 60 * 24 * 365, { leading: true }), '365:00:00:00', 'check 365 days is too long to care') + t.end() +}) + test('is ES5', function (t) { t.equal(isES5(src), true, 'is ES5') t.end()