Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String format for getting the day of the month without leading zero

I'm trying to use string formatting on a DateTime object in C# to get the day of the month without leading zeros.

After some searching I found some documentation for DateTime formats, which shows that I should be able to call:

dateTime.ToString("d");

to get the value I'm after, however when I tried it, instead of receiving a number like 28, the output was: 3/28/2013.

After a bit more searching I found documentation for the Standard Date and Time String Formats.

Both sets of formats make use of the "d" format, but it is apparent by the results that the standard string format is taking precedence over the custom string format.

Is there a way to specify which formatting is desired?

For code consistency I'd prefer to write:

a = dateTime.ToString(...some format...);
b = dateTime.ToString(...some format...);

rather than

a = dateTime.ToString(...some format...);
b = dateTime.Day.ToString();
like image 624
zzzzBov Avatar asked Mar 28 '13 16:03

zzzzBov


1 Answers

A single character is understood to be a Standard Date and Time Format String, in this case the "Short date pattern".

You need to prefix a single character custom format string with % for it to be interpreted as a custom one:

dateTime.ToString("%d");

This is described on the page you linked to, under Using Single Custom Format Specifiers (which describes the % custom format specifier).

like image 86
Oded Avatar answered Oct 02 '22 15:10

Oded