0

Need to create a buffer from UNIX timestamp to save it on bsv blockchain. Tried this solution:

let buffer = Buffer.allocUnsafe(10);
buffer.writeUInt16BE(Date.now());

But getting an error:

RangeError [ERR_OUT_OF_RANGE]: The value of "value" is out of range. It must be >= 0 and <= 65535. Received 1568909911723
    at checkInt (internal/buffer.js:35:11)
    at writeU_Int16BE (internal/buffer.js:653:3)
    at Buffer.writeUInt16BE (internal/buffer.js:661:10)

2 Answers2

0

Try this:

    let bignum = require('bignum');
    let opts= {endian:'big',size:6 /*6-byte / 48-bit*/}
    let dt = Date.now();
    console.log(dt);
    let num = bignum(dt.toString());
    var buf = num.toBuffer(opts);
    let a = bignum.fromBuffer(buf,opts)
    console.log(a.toNumber());

Read this also:nodejs write 64bit unsigned integer to buffer. Will be helpful to understand the core concept.

Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37
0

Unix timestamp usually implies seconds while timestamps in JS contain milliseconds. If you need the milliseconds use Sandeep Patels solution.

If seconds are enough it can be simplified to this:

const seconds = Math.floor(Date.now() / 1000);
const timeBuffer = Buffer.alloc(4, 0x00);
timeBuffer.writeUInt32BE(seconds, 0);
Gigo
  • 3,188
  • 3
  • 29
  • 40