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

Commit 18030d9

Browse files
authored
fix: pad ns correctly (#41)
The nanosecond component of a RFC3339 date should be nine characters long and padded at the front with 0s.
1 parent 4ee950d commit 18030d9

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

src/utils.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ export function toRFC3339 (time: Date) {
1010
const minute = String(time.getUTCMinutes()).padStart(2, '0')
1111
const seconds = String(time.getUTCSeconds()).padStart(2, '0')
1212
const milliseconds = time.getUTCMilliseconds()
13-
const nanoseconds = milliseconds * 1000 * 1000
13+
const nanoseconds = String(milliseconds * 1000 * 1000).padStart(9, '0')
1414

1515
return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`
1616
}

test/record.spec.ts

+12
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,18 @@ describe('record', () => {
2727
expect(dec.timeReceived).to.be.eql(date)
2828
})
2929

30+
it('serialize & deserialize with padding', () => {
31+
// m/d/h/m/s/ms all need padding with 0s when converted to RFC3339 format
32+
const date = new Date('2022-04-03T01:04:08.078Z')
33+
34+
const rec = new Libp2pRecord(uint8ArrayFromString('hello'), uint8ArrayFromString('world'), date)
35+
const dec = Libp2pRecord.deserialize(rec.serialize())
36+
37+
expect(dec).to.have.property('key').eql(uint8ArrayFromString('hello'))
38+
expect(dec).to.have.property('value').eql(uint8ArrayFromString('world'))
39+
expect(dec.timeReceived).to.be.eql(date)
40+
})
41+
3042
describe('go interop', () => {
3143
it('no signature', () => {
3244
const dec = Libp2pRecord.deserialize(fixture.serialized)

test/utils.spec.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const dates = [{
1414
str: '2016-12-30T20:02:05.297000000Z'
1515
}, {
1616
obj: new Date(Date.UTC(2012, 1, 25, 10, 10, 10, 10)),
17-
str: '2012-02-25T10:10:10.10000000Z'
17+
str: '2012-02-25T10:10:10.010000000Z'
1818
}]
1919

2020
describe('utils', () => {

0 commit comments

Comments
 (0)