Fortran

Guide To Learn

Modeling a time interval

Let’s first design a data structure to represent a time interval, or difference. How do we think of time intervals? They can be expressed as a number of days, hours, minutes, seconds, or any combination thereof. You may ask, Why not simply express the time difference as a finite number of days or seconds, like the UNIX time I mentioned earlier? While this is certainly useful for internal calculations, we also need a human-readable format for a time interval to display it as the output of the program. This is where the timedelta class comes in. We can use the familiar syntax to create a derived type timedelta to model this data structure:

type :: timedelta
  integer :: days = 0, hours = 0, &       ❶
             minutes = 0, seconds = 0     ❶
end type timedelta

❶ All optional, integer components

timedelta class is even simpler than the datetime class. Here we have only four integer components (days, hours, minutes, and seconds), and all are optional. This makes timedelta more flexible than datetime as well. If no arguments are provided to the timedelta constructor, a zero timedelta instance will be created. You may ask why we haven’t included the months or years as components as well. It’s because both months and years can be of different absolute time lengths. For example, February is always shorter than March in terms of absolute time, and they’re both exactly one month. The same goes for leap and nonleap years.

Modeling a time interval

Leave a Reply

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

Scroll to top