Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import * as C from './constant'

const padStart = (string, length, pad) => {
const s = String(string)
if (!s || s.length >= length) return string
return `${Array((length + 1) - s.length).join(pad)}${string}`
const neg = s[0] === '-'
const abs = neg ? s.slice(1) : s
if (!abs || abs.length >= length) return string
return `${neg ? '-' : ''}${Array((length + 1) - abs.length).join(pad)}${abs}`
}

const padZoneStr = (instance) => {
Expand Down
11 changes: 11 additions & 0 deletions test/display.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,17 @@ it('As ISO 8601 String -> toISOString e.g. 2013-02-04T22:44:30.652Z', () => {
expect(dayjs().toISOString()).toBe(moment().toISOString())
})

it('Negative years formatted with YYYY keep the sign and pad with zeroes', () => {
[[-1, '-0001'], [-10, '-0010'], [-100, '-0100'], [-1000, '-1000']].forEach(([year, expected]) => {
const date = new Date(0)
date.setFullYear(year, 5, 15) // mid-year so the local timezone cannot shift the year
expect(dayjs(date).format('YYYY')).toBe(expected)
expect(dayjs(date).format('YYYY')).toBe(moment(date).format('YYYY'))
})
expect(dayjs('-000001-06-15').format('YYYY')).toBe('-0001')
expect(dayjs('-000001-06-15').year()).toBe(-1)
})

it('Year 1 formatted with YYYY should pad with zeroes', () => {
const date = new Date(1, 0, 1)
date.setUTCFullYear(1) // Required because 0-99 are parsed as 19xx in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#year
Expand Down
10 changes: 10 additions & 0 deletions test/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,14 @@ it('PadZoneStr', () => {
it('PadStart', () => {
expect(padStart(1, 2, '0')).toBe('01')
expect(padStart(0, 2, '0')).toBe('00')
expect(padStart(123, 2, '0')).toBe(123)
expect(padStart('', 2, '0')).toBe('')
})

it('PadStart keeps the sign of negative numbers', () => {
expect(padStart(-1, 4, '0')).toBe('-0001')
expect(padStart(-10, 4, '0')).toBe('-0010')
expect(padStart(-100, 4, '0')).toBe('-0100')
expect(padStart(-1000, 4, '0')).toBe(-1000)
expect(padStart(-10000, 4, '0')).toBe(-10000)
})