Time in TypeScript

import * as moment from 'moment';

function main() {
    const p = console.log;

    // We'll start by getting the current time.
    const now = moment();
    p(now.format());

    // You can build a moment object by providing the
    // year, month, day, etc. Times are always associated
    // with a time zone.
    const then = moment.utc([2009, 10, 17, 20, 34, 58, 651]);
    p(then.format());

    // You can extract the various components of the time
    // value as expected.
    p(then.year());
    p(then.month() + 1);  // moment uses 0-indexed months
    p(then.date());
    p(then.hour());
    p(then.minute());
    p(then.second());
    p(then.millisecond());
    p(then.utcOffset());

    // The day of the week is also available.
    p(then.day());

    // These methods compare two times, testing if the
    // first occurs before, after, or at the same time
    // as the second, respectively.
    p(then.isBefore(now));
    p(then.isAfter(now));
    p(then.isSame(now));

    // The diff method returns a Duration representing
    // the interval between two times.
    const diff = moment.duration(now.diff(then));
    p(diff.humanize());

    // We can compute the length of the duration in
    // various units.
    p(diff.asHours());
    p(diff.asMinutes());
    p(diff.asSeconds());
    p(diff.asMilliseconds());

    // You can use add to advance a time by a given
    // duration, or subtract to move backwards by a
    // duration.
    p(then.add(diff).format());
    p(then.subtract(diff).format());
}

main();

This TypeScript code demonstrates working with dates and times using the Moment.js library, which provides functionality similar to Go’s time package.

To run this program, you’ll need to have Node.js and the Moment.js library installed. You can install Moment.js using npm:

$ npm install moment

Then, you can run the program using ts-node or by compiling it to JavaScript first:

$ ts-node time.ts

Or:

$ tsc time.ts
$ node time.js

The output will be similar to the Go version, showing various date and time operations and comparisons.

Note that TypeScript (and JavaScript) don’t have built-in nanosecond precision, so we’re using milliseconds instead. Also, the Weekday() method is replaced with day(), which returns a number (0-6) representing the day of the week.

The concepts of time zones, duration calculations, and time comparisons are all present in this TypeScript version, making it a close equivalent to the original Go code.