Time in F#

open System

// We'll start by getting the current time.
let now = DateTime.Now
printfn "%A" now

// You can build a DateTime struct by providing the
// year, month, day, etc. DateTimes are always associated
// with a DateTimeKind, i.e. Local, Utc, or Unspecified.
let then = DateTime(2009, 11, 17, 20, 34, 58, 651, DateTimeKind.Utc)
printfn "%A" then

// You can extract the various components of the DateTime
// value as expected.
printfn "%d" then.Year
printfn "%A" then.Month
printfn "%d" then.Day
printfn "%d" then.Hour
printfn "%d" then.Minute
printfn "%d" then.Second
printfn "%d" then.Millisecond
printfn "%A" then.Kind

// The Monday-Sunday DayOfWeek is also available.
printfn "%A" then.DayOfWeek

// These methods compare two DateTimes, testing if the
// first occurs before, after, or at the same time
// as the second, respectively.
printfn "%b" (then < now)
printfn "%b" (then > now)
printfn "%b" (then = now)

// The subtract operator returns a TimeSpan representing
// the interval between two DateTimes.
let diff = now - then
printfn "%A" diff

// We can compute the length of the duration in
// various units.
printfn "%f" diff.TotalHours
printfn "%f" diff.TotalMinutes
printfn "%f" diff.TotalSeconds
printfn "%f" diff.TotalMilliseconds

// You can use Add to advance a DateTime by a given
// TimeSpan, or with a negative TimeSpan to move backwards.
printfn "%A" (then.Add(diff))
printfn "%A" (then.Add(-diff))

This F# code demonstrates working with dates and times. Here’s a breakdown of what it does:

  1. We start by getting the current time using DateTime.Now.

  2. We create a specific DateTime using the DateTime constructor, specifying year, month, day, hour, minute, second, millisecond, and kind (UTC in this case).

  3. We extract various components of the DateTime (year, month, day, etc.) and print them.

  4. We demonstrate the DayOfWeek property.

  5. We compare two DateTimes using the <, >, and = operators.

  6. We calculate the difference between two DateTimes, which gives us a TimeSpan.

  7. We show various properties of the TimeSpan (hours, minutes, seconds, milliseconds).

  8. Finally, we demonstrate adding and subtracting a TimeSpan to/from a DateTime.

Note that F# uses DateTime and TimeSpan from the .NET framework, which offer similar functionality to Go’s time.Time and time.Duration. The main difference is that F# doesn’t have nanosecond precision, it goes down to milliseconds.

To run this program, save it as a .fs file (e.g., time_example.fs) and use the F# compiler:

$ fsharpc time_example.fs
$ mono time_example.exe

This will compile and run the F# program, showing the various date and time operations.