mrturtle
mrturtle

Reputation: 297

How to print formatted date in F#

I have this date in F#

let myDate = new DateTime(2015, 06, 02)

And want to output it like "2015/06/02" in the console window. I tried:

Console.WriteLine(sprintf "%s" myDate.ToString("yyyy/MM/dd"))

But this does not compile (compiler says, "Successive arguments should be separated by spaces or tupled, and arguments involving function or method applications should be parenthesized")

How would I output the date as "2015/06/02"?

UPDATE:

As commented by Panagiotis Kanavos, this will work:

Console.WriteLine("{0:yyyy/MM/dd}", myDate)

Upvotes: 15

Views: 6530

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233202

You easily can call the ToString overload that takes a format string:

let formatted = myDate.ToString "yyyy/MM/dd"

However, sprintf doesn't support that in short form, but you could do this:

printfn "%s" (myDate.ToString "yyyy/MM/dd")

You can also define a function for this purpose, if you feel that calling a method on an object isn't sufficiently functional:

let inline stringf format (x : ^a) = 
    (^a : (member ToString : string -> string) (x, format))

which would enable you to compose functions in many interesting ways. You could for example write to the console like this:

myDate |> stringf "yyyy/MM/dd" |> printfn "%s"

or like this:

(stringf "yyyy/MM/dd" >> printfn "%s") myDate

Upvotes: 22

Related Questions