.NET DateTime Day format without a leading zero

For the following code, I expect the result to be 2, because MSDN states that 'd' "Represents the day of the month as a number from 1 to 31. The single-day is formatted without a leading zero.".

DateTime myDate = new DateTime( 2009, 6, 4 ); string result = myDate.ToString( "d" ); 

However, the result is actually β€œ6/4/2009” - this is a short date format (which is also β€œd”). I could use 'dd', but that adds the leading zero, which I don't want.

+18
c # datetime formatting
Jun 12 '09 at 18:48
source share
2 answers

To indicate that this is a specifier of a special format (as opposed to a specifier of a standard format), it must contain two characters. This can be done by adding a space (which will be displayed on the output) or by including a percent sign in front of one letter, for example:

 string result = myDate.ToString("%d"); 

MSDN

+38
Jun 12 '09 at 18:48
source share

Instead of using string formatting strings, how about using the Day property

 DateTime myDate = new DateTime(2009,6,4) int result = myDate.Day; 

Or if you really need the result in string format

 string result = myDate.Day.ToString(); 

If you want to get a specific date from a date object, rather than a formatted representation of the date, I prefer to use properties (Day, Month, Year, DayOfWeek, etc.). It makes reading the code a little easier (especially if someone else reads / supports it that doesn't remember the different formatting codes)

+5
Jun 12 '09 at 20:52
source share



All Articles