Skip to content

Commit 55da5a9

Browse files
datastore: use millisecond-precision with stored dates
1 parent 898736b commit 55da5a9

File tree

3 files changed

+15
-11
lines changed

3 files changed

+15
-11
lines changed

packages/datastore/src/entity.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,8 @@ function decodeValueProto(valueProto) {
191191
}
192192

193193
case 'timestampValue': {
194-
return new Date(parseInt(value.seconds, 10) * 1000);
194+
var milliseconds = parseInt(value.nanos, 10) / 1e6;
195+
return new Date(parseInt(value.seconds, 10) * 1000 + milliseconds);
195196
}
196197

197198
default: {
@@ -252,11 +253,10 @@ function encodeValue(value) {
252253

253254
if (value instanceof Date) {
254255
var seconds = value.getTime() / 1000;
255-
var secondsRounded = Math.floor(seconds);
256256

257257
valueProto.timestampValue = {
258-
seconds: secondsRounded,
259-
nanos: Math.floor((seconds - secondsRounded) * 1e9)
258+
seconds: Math.floor(seconds),
259+
nanos: value.getMilliseconds() * 1e6
260260
};
261261

262262
return valueProto;

packages/datastore/system-test/datastore.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ describe('Datastore', function() {
7171
var post = {
7272
title: 'How to make the perfect pizza in your grill',
7373
tags: ['pizza', 'grill'],
74-
publishedAt: new Date(2001, 0, 1),
74+
publishedAt: new Date(),
7575
author: 'Silvano',
7676
isDraft: false,
7777
wordCount: 400,

packages/datastore/test/entity.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -218,13 +218,18 @@ describe('entity', function() {
218218
});
219219

220220
it('should decode timestamps', function() {
221-
var seconds = String(Date.now() / 1000);
222-
var expectedValue = new Date(parseInt(seconds, 10) * 1000);
221+
var date = new Date();
222+
223+
var seconds = Math.floor(date.getTime() / 1000);
224+
var ms = date.getMilliseconds();
225+
226+
var expectedValue = new Date(seconds * 1000 + ms);
223227

224228
var valueProto = {
225229
value_type: 'timestampValue',
226230
timestampValue: {
227-
seconds: seconds
231+
seconds: seconds,
232+
nanos: ms * 1e6
228233
}
229234
};
230235

@@ -327,12 +332,11 @@ describe('entity', function() {
327332
it('should encode a date', function() {
328333
var value = new Date();
329334
var seconds = value.getTime() / 1000;
330-
var secondsRounded = Math.floor(seconds);
331335

332336
var expectedValueProto = {
333337
timestampValue: {
334-
seconds: secondsRounded,
335-
nanos: Math.floor((seconds - secondsRounded) * 1e9)
338+
seconds: Math.floor(seconds),
339+
nanos: value.getMilliseconds() * 1e6
336340
}
337341
};
338342

0 commit comments

Comments
 (0)