Fortran

Guide To Learn

Calculating the difference between two times

Finally, we get to the meat of the countdown app: calculating the difference between the two times. There are three necessary ingredients for this to work:

  • A data structure to represent a time interval–a timedelta class
  • A syntax to define a subtraction operator for datetime instances
  • An algorithm to calculate the difference

At the end of this section, we’ll be able to initialize two datetimes and take their difference, which should look something like this:

type(datetime) :: now, birthday      ❶
type(timedelta) :: td                ❷
 
call get_date_from_cli(birthday)     ❸
now = current_time()                 ❹
td = birthday - now                  ❺

❶ Two datetime instances

❷ One timedelta instance

❸ Gets the date from the command line

❹ Gets the current date and time

❺ Takes the difference using the arithmetic operator –

We’re already able to declare datetime instances and initialize them either from the command line (get_date_from_cli) or from machine time (current_time). What we don’t know how to do yet, and neither does the compiler, is take the difference between two datetimes using nothing but an arithmetic subtraction (-) operator and make it return a timedelta instance. The next section tackles that problem.

Calculating the difference between two times

Leave a Reply

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

Scroll to top