Robert Koritnik
Robert Koritnik

Reputation: 105091

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?

Upvotes: 7

Views: 4274

Answers (5)

Jon Hanna
Jon Hanna

Reputation: 113392

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

Upvotes: 4

Kristoffer Lindvall
Kristoffer Lindvall

Reputation: 2682

How about:

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

Upvotes: 9

Yngve B-Nilsen
Yngve B-Nilsen

Reputation: 9676

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.

Upvotes: 0

Kieren Johnstone
Kieren Johnstone

Reputation: 42023

If nothing else, you could: x.ToString("ddd", ci) + " " + x.ToString("d", ci);

Upvotes: 0

Snowbear
Snowbear

Reputation: 17274

x.ToString("ddd ", ci) + x.ToString("d", ci);

Upvotes: 1

Related Questions