如何在F#中打印格式化的日期 [英] How to print formatted date in F#

查看:91
本文介绍了如何在F#中打印格式化的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在F#中有这个日期

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

并希望在控制台窗口中将其输出为"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")

如何将日期输出为"2015/06/02"?

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

更新:

如Panagiotis Kanavos所说,这将起作用:

As commented by Panagiotis Kanavos, this will work:

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

推荐答案

您可以轻松地调用采用格式字符串的ToString重载:

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

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

但是,sprintf不支持简写形式,但是您可以这样做:

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"

或类似这样:

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

这篇关于如何在F#中打印格式化的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆