Epoch in Julia

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

using Dates

# Use `now()` to get the current time
current_time = now()
println(current_time)

# Get elapsed time since the Unix epoch in seconds, milliseconds, or nanoseconds
println(datetime2unix(current_time))
println(round(Int, datetime2unix(current_time) * 1000))
println(round(Int, datetime2unix(current_time) * 1e9))

# Convert integer seconds or nanoseconds since the epoch into the corresponding DateTime
println(unix2datetime(datetime2unix(current_time)))
println(unix2datetime(datetime2unix(current_time)))

Use now() to get the current time, and then use datetime2unix() to convert it to seconds since the Unix epoch. Multiply by 1000 or 1e9 to get milliseconds or nanoseconds, respectively.

You can also convert integer seconds since the epoch back into the corresponding DateTime using unix2datetime().

To run the program:

$ julia epoch.jl
2023-05-24T12:34:56.789
1684932896.789
1684932896789
1684932896789000000
2023-05-24T12:34:56.789
2023-05-24T12:34:56.789

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