Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format .NET DateTime "Day" with no leading zero

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

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

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

like image 863
Marcel Lamothe Avatar asked Jun 12 '09 18:06

Marcel Lamothe


People also ask

How to set format DateTime in c#?

It should be formatted like this: myDateTime. ToString("yyyy/MM/dd hh:mm:ss"); or myDateTime. ToString("yyyy/MM/dd); Because mm is for minute and for month MM should be used.

What is T and Z in time format?

The T is just a literal to separate the date from the time, and the Z means “zero hour offset” also known as “Zulu time” (UTC). If your strings always have a “Z” you can use: SimpleDateFormat format = new SimpleDateFormat( “yyyy-MM-dd'T'HH:mm:ss).

What is FFF in time format?

The "fff" custom format specifier represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.


1 Answers

To indicate that this is a custom format specifier (in contrast to a standard format specifier), it must be two characters long. This can be accomplished by adding a space (which will show up in the output), or by including a percent sign before the single letter, like this:

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

See documentation

like image 72
Marcel Lamothe Avatar answered Oct 04 '22 05:10

Marcel Lamothe