Fortran

Guide To Learn

Getting current date and time

We got the date from the user input, and now we need to get the current date and time. Fortran provides a subroutine date_and_time that gives you access to the current local machine time. Here’s how it works, wrapped in a function to return a datetime instance:

type(datetime) function current_time() result(res)
  integer :: values(8)                                     ❶
  call date_and_time(values=values)                        ❷
  res = datetime(year = values(1), month = values(2),&     ❸
                 day = values(3), hour = values(5),&       ❸
                 minute = values(6), second = values(7))   ❸
end function current_time

❶ Array of eight integers

❷ Gets the date and time values and stores them into the array

❸ Creates a new datetime instance using these values

This function is short and sweet. We first call the built-in date_and_time with the integer array values with eight elements. Then, we use several of these elements to create a datetime instance and return it as the result. Why is values an array with exactly eight elements, and why do we use only six? See the next sidebar for more information.

The date_and_time built-in subroutine

date_and_time gets the date and time information from the real-time system clock. This is the clock in your computer. There are a few different ways you could use date_and_time. The full syntax is

date_and_time(date, time, zone, values)

where

  • date is a character string of length 8 or larger. If provided, it’s populated with the current date in the form YYYYmmdd (year, month, day).
  • time is a character string of length 10 or larger. If provided, it’s populated with the current time in the form hhmmss.sss (hour, minute, second, millisecond).
  • zone is a character string of length 5 and has the form (+-)hhmm, representing the difference relative to the Coordinated Universal Time (UTC).
  • values is an integer array of size 8, whose elements are year, month, day, time difference from UTC in minutes, hour, minute, second, and millisecond, respectively.

All four arguments to this subroutine are optional.

Getting current date and time

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top