简体   繁体   中英

DateTime.ToString formatting

I'm displaying localized short dates by providing culture info to DateTime.ToString method. 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.

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 . 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.

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/

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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