Epoch in TypeScript

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in TypeScript.

// Use Date.now() to get the current timestamp in milliseconds
const now = new Date();
console.log(now);

// Get seconds since Unix epoch
console.log(Math.floor(now.getTime() / 1000));

// Get milliseconds since Unix epoch
console.log(now.getTime());

// Get nanoseconds since Unix epoch (approximated)
console.log(now.getTime() * 1_000_000);

// You can also convert a timestamp back to a Date object
console.log(new Date(Math.floor(now.getTime() / 1000) * 1000));
console.log(new Date(now.getTime()));

To run this TypeScript code, you’ll need to compile it to JavaScript first and then run it with Node.js:

$ tsc epoch.ts
$ node epoch.js
2023-05-15T12:34:56.789Z
1684154096
1684154096789
1684154096789000000
2023-05-15T12:34:56.000Z
2023-05-15T12:34:56.789Z

In TypeScript, we use the Date object to work with timestamps. Unlike Go, TypeScript doesn’t have built-in methods for Unix time in seconds or nanoseconds, so we need to perform some calculations:

  • To get seconds, we divide the millisecond timestamp by 1000 and floor the result.
  • To get nanoseconds, we multiply the millisecond timestamp by 1,000,000 (this is an approximation, as JavaScript doesn’t have nanosecond precision).

Also, when converting back from a timestamp to a Date object, we need to multiply by 1000 if we’re working with seconds, as Date constructor expects milliseconds.

Next, we’ll look at another time-related task: date parsing and formatting in TypeScript.