Skip to content
This repository has been archived by the owner on Jul 21, 2023. It is now read-only.

Commit

Permalink
fix: pad ns correctly (#41)
Browse files Browse the repository at this point in the history
The nanosecond component of a RFC3339 date should be nine characters long and padded at the front with 0s.
  • Loading branch information
achingbrain authored Apr 14, 2022
1 parent 4ee950d commit 18030d9
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function toRFC3339 (time: Date) {
const minute = String(time.getUTCMinutes()).padStart(2, '0')
const seconds = String(time.getUTCSeconds()).padStart(2, '0')
const milliseconds = time.getUTCMilliseconds()
const nanoseconds = milliseconds * 1000 * 1000
const nanoseconds = String(milliseconds * 1000 * 1000).padStart(9, '0')

return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`
}
Expand Down
12 changes: 12 additions & 0 deletions test/record.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ describe('record', () => {
expect(dec.timeReceived).to.be.eql(date)
})

it('serialize & deserialize with padding', () => {
// m/d/h/m/s/ms all need padding with 0s when converted to RFC3339 format
const date = new Date('2022-04-03T01:04:08.078Z')

const rec = new Libp2pRecord(uint8ArrayFromString('hello'), uint8ArrayFromString('world'), date)
const dec = Libp2pRecord.deserialize(rec.serialize())

expect(dec).to.have.property('key').eql(uint8ArrayFromString('hello'))
expect(dec).to.have.property('value').eql(uint8ArrayFromString('world'))
expect(dec.timeReceived).to.be.eql(date)
})

describe('go interop', () => {
it('no signature', () => {
const dec = Libp2pRecord.deserialize(fixture.serialized)
Expand Down
2 changes: 1 addition & 1 deletion test/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const dates = [{
str: '2016-12-30T20:02:05.297000000Z'
}, {
obj: new Date(Date.UTC(2012, 1, 25, 10, 10, 10, 10)),
str: '2012-02-25T10:10:10.10000000Z'
str: '2012-02-25T10:10:10.010000000Z'
}]

describe('utils', () => {
Expand Down

0 comments on commit 18030d9

Please sign in to comment.