Epoch in Standard ML

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 Standard ML.

structure Time = Time

fun main () =
    let
        (* Use Time.now() to get the current time *)
        val now = Time.now()
        val _ = print (Time.toString now ^ "\n")

        (* Convert to seconds since epoch *)
        val seconds = Time.toSeconds now
        val _ = print (LargeInt.toString seconds ^ "\n")

        (* Convert to milliseconds since epoch *)
        val milliseconds = Time.toMilliseconds now
        val _ = print (LargeInt.toString milliseconds ^ "\n")

        (* Convert to microseconds since epoch *)
        val microseconds = Time.toMicroseconds now
        val _ = print (LargeInt.toString microseconds ^ "\n")

        (* Convert seconds back to Time *)
        val time_from_seconds = Time.fromSeconds seconds
        val _ = print (Time.toString time_from_seconds ^ "\n")

        (* Convert microseconds back to Time *)
        val time_from_microseconds = Time.fromMicroseconds microseconds
        val _ = print (Time.toString time_from_microseconds ^ "\n")
    in
        ()
    end

val _ = main()

In this Standard ML code, we use the Time structure to work with time-related operations. Here’s a breakdown of what the code does:

  1. We use Time.now() to get the current time.
  2. We print the current time as a string using Time.toString.
  3. We convert the time to seconds since the Unix epoch using Time.toSeconds.
  4. We convert the time to milliseconds since the Unix epoch using Time.toMilliseconds.
  5. We convert the time to microseconds since the Unix epoch using Time.toMicroseconds. Note that Standard ML doesn’t have a built-in nanosecond precision, so we use microseconds instead.
  6. We demonstrate how to convert seconds back to a Time value using Time.fromSeconds.
  7. We also show how to convert microseconds back to a Time value using Time.fromMicroseconds.

To run this program, you would typically save it to a file (e.g., epoch.sml) and then use an Standard ML interpreter or compiler to execute it. The exact command might vary depending on your Standard ML implementation, but it could look something like this:

$ sml epoch.sml
2023-05-10 12:34:56.789000
1683722096
1683722096789
1683722096789000
2023-05-10 12:34:56.000000
2023-05-10 12:34:56.789000

Note that the actual output will depend on the current time when you run the program.

Standard ML’s Time structure provides a robust way to work with time and epochs, although it may not have the exact same functions as Go. The concepts, however, remain similar.