Epoch in Miranda

Here’s the translated code and explanation in Markdown format suitable for Hugo:

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 Java.

import java.time.Instant;

public class Epoch {
    public static void main(String[] args) {
        // Use Instant.now() to get the current time
        Instant now = Instant.now();
        System.out.println(now);

        // Get elapsed time since the Unix epoch in seconds,
        // milliseconds or nanoseconds
        System.out.println(now.getEpochSecond());
        System.out.println(now.toEpochMilli());
        System.out.println(now.getNano());

        // You can also convert integer seconds or nanoseconds
        // since the epoch into the corresponding Instant
        System.out.println(Instant.ofEpochSecond(now.getEpochSecond()));
        System.out.println(Instant.ofEpochSecond(0, now.getNano()));
    }
}

To run the program:

$ javac Epoch.java
$ java Epoch
2023-05-25T12:34:56.789Z
1685018096
1685018096789
789000000
2023-05-25T12:34:56Z
1970-01-01T00:00:00.789Z

In Java, we use the Instant class from the java.time package to work with timestamps. The Instant.now() method gives us the current time, and we can use various methods to get the epoch time in different units.

The getEpochSecond() method returns the number of seconds since the epoch, toEpochMilli() returns milliseconds, and getNano() returns the nanosecond adjustment to the second.

We can also create an Instant from epoch seconds or nanoseconds using the ofEpochSecond() method.

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