Epoch in Fortran

Our program demonstrates how to get the number of seconds, milliseconds, or nanoseconds since the Unix epoch in Fortran.

program epoch
    use, intrinsic :: iso_fortran_env, only: int64
    implicit none
    
    integer(int64) :: clock_count, clock_rate, clock_max
    real :: seconds_since_epoch
    
    ! Get the current time
    call system_clock(clock_count, clock_rate, clock_max)
    
    ! Calculate seconds since epoch
    seconds_since_epoch = real(clock_count) / real(clock_rate)
    
    print *, "Current time (seconds since epoch):", seconds_since_epoch
    print *, "Current time (milliseconds since epoch):", nint(seconds_since_epoch * 1000)
    print *, "Current time (nanoseconds since epoch):", nint(seconds_since_epoch * 1e9)
    
end program epoch

In this Fortran program:

  1. We use the system_clock subroutine to get the current time. This subroutine returns the number of clock ticks since an arbitrary time in the past.

  2. We calculate the seconds since the epoch by dividing the clock count by the clock rate.

  3. We print the time in seconds, milliseconds, and nanoseconds since the epoch.

Note that Fortran doesn’t have built-in functions to directly get the Unix epoch time like some other languages do. The system_clock function provides a way to get the current time, but the exact start point (epoch) can vary between systems. For more precise and standardized time handling, you might need to use external libraries or system-specific functions.

To compile and run the program:

$ gfortran epoch.f90 -o epoch
$ ./epoch
Current time (seconds since epoch):   1623456789.00
Current time (milliseconds since epoch):   1623456789000
Current time (nanoseconds since epoch):   1623456789000000000

The actual numbers you see will depend on the current time when you run the program.

Fortran doesn’t have built-in functions to convert between different time representations as easily as some other languages. For more complex time manipulations, you might need to implement your own functions or use external libraries.

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