How to print formatted date in F#

亡梦爱人 提交于 2019-12-22 10:46:52

问题


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)

回答1:


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


来源:https://stackoverflow.com/questions/30590473/how-to-print-formatted-date-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!