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.
To run this TypeScript code, you’ll need to compile it to JavaScript first and then run it with Node.js:
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.