C# - 如何使用DateTime.ToString显示Apr '11

17

我已经尝试了各种方法,使用DateTime ToString方法来呈现一个Apr '11格式的日期。文档中说'被保留用于字符串字面量,所以我认为要显示单引号,应该使用'''' - 然而,不起作用。到目前为止,这是我尝试过的:

taskdata.Month.Start.ToString("MMM 'yy")
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
taskdata.Month.Start.ToString("MMM ''yy")
"Apr 09"
taskdata.Month.Start.ToString("MMM '''yy")
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
taskdata.Month.Start.ToString("MMM ''''yy")
"Apr 09"
taskdata.Month.Start.ToString("MMM \'yy")
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
taskdata.Month.Start.ToString("MMM '\''yy")
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

说真的,有什么秘诀吗?我不想使用字符串连接!


我拒绝连接!为什么不这样做?浪费时间,而你可以自己实现并完成它。 - Ed S.
3
你是否曾经接手过代码,然后心想:"为什么他们不用简单的方法呢?显然那个人不会编码。" 是的,我不想在未来成为“那个人”。 - Mike Christensen
4
@EdS. 要写出更好的代码。学习新事物。迎接挑战(通过向他人提问,尝试并失败 :))。 - Otiel
嘿,我最终会想出来的...大概。 - Mike Christensen
@Otiel:同意。我没有意识到这只是一个简单的字符转义问题,读得太快了。 - Ed S.
2个回答

44

你需要进行转义(实际上是双重转义):

new DateTime(2011, 10, 1).ToString("MMM \\'yy")

15
请注意,如果您使用原文字符串字面值,则无需双重转义:@"MMM \'yy" - Jon Skeet

10
String.Format(@"{0:MMM  \'yy}", DateTime.Now)

对我有用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接