Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String.Format to get Month Number

Status
Not open for further replies.

tshad

Programmer
Jul 15, 2004
386
0
0
US
I need to get the month number from a date using String.Format. But it doesn't seem to work correctly.

string.Format("{0:M}", entity.OrderPeriodDate)

Comes back with "June 15" and not 6 as many posts say.

string.Format("{0:MM}", entity.OrderPeriodDate)

Comes back with "06".

I need to get it without the leading zero. "M" is supposed to do that.

How can I get this correctly?

Thanks,

Tom
 
The 'M' is being interpreted as a standard (not custom) date format specifier.

The specifications state:

The "M" custom format specifier represents the month as a number from 1 through 12 (or from 1 through 13 for calendars that have 13 months). A single-digit month is formatted without a leading zero.

If the "M" format specifier is used without other custom format specifiers, it is interpreted as the "M" standard date and time format specifier.


To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" custom format specifier by itself), include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier.
 
@elconomeno,

You're on the right path. If he just needs the month, then String.format() is over kill. You can collapse your solution down further.

Code:
entity.OrderPeriodDate.Month.ToString();

Lodlaiden

You've got questions and source code. We want both!
There's a whole lot of Irish in that one.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top