Skip to content

Commit 78d29be

Browse files
committed
Add Timestamp
1 parent 8fe31b9 commit 78d29be

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/timestamp.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
3+
function Timestamp(seconds, nanoseconds) {
4+
this.seconds = seconds;
5+
this.nanoseconds = nanoseconds;
6+
}
7+
8+
Timestamp.fromDate = function(date) {
9+
var sec = Math.floor(date.getTime() / 1000);
10+
var ns = (date.getTime() % 1000) * 1000 * 1000;
11+
return new Timestamp(sec, ns);
12+
};
13+
14+
Timestamp.prototype.toDate = function () {
15+
var millis = this.seconds * 1000 + this.nanoseconds / (1000 * 1000);
16+
return new Date(millis);
17+
};
18+
19+
module.exports = Timestamp;

test/unit/timestamp.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
'use strict';
2+
3+
var expect = require('chai').use(require('sinon-chai')).expect;
4+
var sinon = require('sinon');
5+
var Timestamp = require('../../src/timestamp');
6+
7+
describe('Timestamp', function () {
8+
describe('fromDate', function () {
9+
it('should convert from date', function () {
10+
var date = new Date('2009-02-13T23:31:30.123456789Z');
11+
var timestamp = Timestamp.fromDate(date);
12+
expect(timestamp.seconds).to.equal(1234567890);
13+
expect(timestamp.nanoseconds).to.equal(123000000);
14+
});
15+
});
16+
describe('#toDate', function () {
17+
it('should convert to date', function () {
18+
var ts = new Timestamp(1234567890, 123456789);
19+
var date = ts.toDate();
20+
expect(date.toISOString()).to.equal('2009-02-13T23:31:30.123Z');
21+
});
22+
});
23+
});

0 commit comments

Comments
 (0)