Time Formatting Parsing in F#

Our first example demonstrates time formatting and parsing in F#. Here’s the full source code:

open System

let printDateTime (dt: DateTime) (format: string) =
    printfn "%s" (dt.ToString(format))

let parseDateTime (s: string) (format: string) =
    match DateTime.TryParseExact(s, format, null, Globalization.DateTimeStyles.None) with
    | true, dt -> Some dt
    | _ -> None

[<EntryPoint>]
let main argv =
    let now = DateTime.Now

    // Basic example of formatting a time according to ISO 8601
    printDateTime now "o"

    // Time parsing uses the same format strings as ToString
    match parseDateTime "2012-11-01T22:08:41+00:00" "o" with
    | Some dt -> printfn "%A" dt
    | None -> printfn "Failed to parse"

    // Custom format strings
    printDateTime now "h:mmtt"
    printDateTime now "ddd MMM dd HH:mm:ss yyyy"
    printDateTime now "yyyy-MM-ddTHH:mm:ss.fffffffzzz"

    // Parsing with custom format
    let customFormat = "h mm tt"
    match parseDateTime "8 41 PM" customFormat with
    | Some dt -> printfn "%A" dt
    | None -> printfn "Failed to parse"

    // For purely numeric representations you can also use string interpolation
    printfn "%04d-%02d-%02dT%02d:%02d:%02d+00:00" 
        now.Year now.Month now.Day now.Hour now.Minute now.Second

    // Parsing will return None on malformed input
    match parseDateTime "8:41PM" "ddd MMM dd HH:mm:ss yyyy" with
    | Some _ -> printfn "Parsed successfully"
    | None -> printfn "Failed to parse"

    0

F# supports time formatting and parsing via format strings, similar to other .NET languages.

The DateTime.ToString() method is used for formatting, while DateTime.TryParseExact() is used for parsing. We’ve wrapped these in helper functions for easier use.

Here’s a basic example of formatting a time according to ISO 8601, using the corresponding format string.

Time parsing uses the same format strings as ToString().

F# uses format strings for both formatting and parsing. These strings use patterns like “yyyy” for year, “MM” for month, “dd” for day, etc. The DateTime struct provides many standard format strings, or you can create custom ones.

For purely numeric representations, you can also use string interpolation with the extracted components of the time value.

Parsing will return None on malformed input, which we can handle using pattern matching.

When you run this program, you’ll see output demonstrating various formatted dates and times, as well as the results of parsing operations.

This example showcases F#’s strong type system and pattern matching, which make working with dates and times both safe and expressive.