Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print formatted date in F#

Tags:

.net

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)
like image 677
mrturtle Avatar asked Jun 02 '15 07:06

mrturtle


People also ask

How do I print a date in a specific format in Python?

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.

How is a date formatted?

The international standard recommends writing the date as year, then month, then the day: YYYY-MM-DD.


1 Answers

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
like image 188
Mark Seemann Avatar answered Sep 24 '22 11:09

Mark Seemann