简体   繁体   English

DateTime.ToString格式

[英]DateTime.ToString formatting

I'm displaying localized short dates by providing culture info to DateTime.ToString method. 我通过向DateTime.ToString方法提供文化信息来显示本地化的短日期。 By now I was using 到现在为止我正在使用

x.ToString("d", ci); // 23.12.2000

that displays short date. 显示短日期。 But now I would like to also include abbreviated day name. 但现在我想也包括缩写日名。 I tried 我试过了

x.ToString("ddd d", ci); // pon 23

but now d becomes day specifier instead of short date format so instead of day name and short date I only get day name and day number. 但现在d成为日期说明符而不是短日期格式,所以我只获取日期名称和日期编号而不是日期名称和短日期。

How do I convince formatter to display day along with predefined culture short date format? 如何说服格式化程序显示日期以及预定义的文化短日期格式?

怎么样:

string.Format(ci, "{0:ddd} {0:d}", x)

The "standard" formatting strings work by obtaining the equivalent property of the CultureInfo 's DateTimeFormat . “标准”格式化字符串通过获取CultureInfoDateTimeFormat的等效属性来工作。 In this case "d" finds the ShortDatePattern property, which will be something like "dd.MM.yyyy", "dd/MM/yyyy", "MM/dd/yyyy", "yyyy-MM-dd" and so on, depending on that locale in question. 在这种情况下, "d"找到ShortDatePattern属性,它将类似于“dd.MM.yyyy”,“dd / MM / yyyy”,“MM / dd / yyyy”,“yyyy-MM-dd”等等,取决于所讨论的区域设置。

Hence you can make use of it in a custom pattern like so: 因此,您可以在自定义模式中使用它,如下所示:

x.ToString("ddd " + ci.DateTimeFormat.ShortDatePattern, ci) // Sat 2000-12-23 on my set up, should presumably be pon 23.12.2000 on yours
x.ToString("ddd ", ci) + x.ToString("d", ci);

Take a look at this explanation: 看看这个解释:

http://www.csharp-examples.net/string-format-datetime/ http://www.csharp-examples.net/string-format-datetime/

Maybe you can find some examples there. 也许你可以在那里找到一些例子。

Update 更新

As response to the comment, Example 3 in the first codeblock clearly states how to do this: 作为对评论的回应,第一个代码块中的示例3清楚地说明了如何执行此操作:

String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day

Googling a question about date to string formatting, and hitting this question will be much more valuable if there is a reference to good examples. 谷歌搜索关于日期的问题到字符串格式,如果有一个好例子的参考,点击这个问题会更有价值。 Hence the reference to the csharp-examples site. 因此引用了csharp-examples站点。

如果没有别的,你可以: x.ToString("ddd", ci) + " " + x.ToString("d", ci) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM