diff --git a/spec/providers/firestore.spec.ts b/spec/providers/firestore.spec.ts index a632d9fa3..e6e72c5d0 100644 --- a/spec/providers/firestore.spec.ts +++ b/spec/providers/firestore.spec.ts @@ -295,7 +295,7 @@ describe('Firestore Functions', () => { expect(snapshot.data()['referenceVal'].path).to.equal('doc1/id'); }); - it('should parse timestamp values', () => { + it('should parse timestamp values with precision to the millisecond', () => { let raw = constructValue({ 'timestampVal': { 'timestampValue': '2017-06-13T00:58:40.349Z', @@ -307,6 +307,19 @@ describe('Firestore Functions', () => { expect(snapshot.data()).to.deep.equal({'timestampVal': new Date('2017-06-13T00:58:40.349Z')}); }); + it('should parse timestamp values with precision to the second', () => { + let raw = constructValue({ + 'timestampVal': { + 'timestampValue': '2017-06-13T00:58:40Z', + }, + }); + let snapshot = firestore.dataConstructor({ + data: { value: raw }, + }); + expect(snapshot.data()).to.deep.equal({'timestampVal': new Date('2017-06-13T00:58:40Z')}); + + }); + it('should parse binary values', () => { // Format defined in https://developers.google.com/discovery/v1/type-format let raw = constructValue({ diff --git a/src/encoder.ts b/src/encoder.ts index 78ddba559..59d3cb223 100644 --- a/src/encoder.ts +++ b/src/encoder.ts @@ -26,16 +26,11 @@ export function dateToTimestampProto(timeString) { } let date = new Date(timeString); let seconds = Math.floor(date.getTime() / 1000); - let nanoString = timeString.substring(20, timeString.length - 1); - - if (nanoString.length === 3) { - nanoString = `${nanoString}000000`; - } else if (nanoString.length === 6) { - nanoString = `${nanoString}000`; + let nanos = 0; + if (timeString.length > 20) { + const nanoString = timeString.substring(20, timeString.length - 1); + const trailingZeroes = 9 - nanoString.length; + nanos = parseInt(nanoString, 10) * Math.pow(10, trailingZeroes); } - let proto = { - seconds: seconds, - nanos: parseInt(nanoString, 10), - }; - return proto; + return { seconds, nanos }; };