使用 DateTime.ToString() 时获取日期后缀 [英] Getting day suffix when using DateTime.ToString()
问题描述
在使用 DateTime.ToString() 格式化日期时是否可以包含日期后缀?
Is it possible to include the day suffix when formatting a date using DateTime.ToString()?
例如,我想以以下格式打印日期 - 2009 年 7 月 27 日星期一.但是,我可以使用 DateTime.ToString() 找到的最接近的示例是 2009 年 7 月 27 日星期一.
For example I would like to print the date in the following format - Monday 27th July 2009. However the closest example I can find using DateTime.ToString() is Monday 27 July 2009.
我可以使用 DateTime.ToString() 来做到这一点,还是我将不得不退回到我自己的代码?
Can I do this with DateTime.ToString() or am I going to have to fall back to my own code?
推荐答案
作为参考,我总是使用/参考 [SteveX String Formatting] 1并且似乎没有任何th"在任何可用变量中,但您可以使用
As a reference I always use/refer to [SteveX String Formatting] 1 and there doesn't appear to be any "th" in any of the available variables but you could easily build a string with
string.Format("{0:dddd dd}{1} {0:MMMM yyyy}", DateTime.Now, (?));
然后你必须提供一个st"对于 1,nd"对于 2,rd"为 3,和th"对于所有其他人,并且可以与?:"声明.
You would then have to supply a "st" for 1, "nd" for 2, "rd" for 3, and "th" for all others and could be in-lined with a "? :" statement.
var now = DateTime.Now;
(now.Day % 10 == 1 && now.Day % 100 != 11) ? "st"
: (now.Day % 10 == 2 && now.Day % 100 != 12) ? "nd"
: (now.Day % 10 == 3 && now.Day % 100 != 13) ? "rd"
: "th"
这篇关于使用 DateTime.ToString() 时获取日期后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!