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)
Use strftime() function of a datetime class The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
The international standard recommends writing the date as year, then month, then the day: YYYY-MM-DD.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With