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();
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With