DateTime.Month
This C# property returns an integer. This value indicates the month in the year, from January to December. With a format string
, we can get month names.
The DateTime
type provides month-related functionality in .NET. We do not need to create it ourselves: to save time and increase program reliability, it is best not to.
Month is an instance property getter in the language, which means you must call it on a DateTime
instance, but not with parentheses.
string
for short
, 3-letter month strings.string
(four Ms) for the complete month name. So Sep turns into September.using System; // Get the current month integer. DateTime now = DateTime.Now; // Write the month integer and then the three-letter month. Console.WriteLine(now.Month); Console.WriteLine(now.ToString("MMM"));5 May
You may need to display the month name in a three-letter format. This is equivalent, in English, to taking a substring of the first three letters.
using System; DateTime now = DateTime.Now; // Loop over all 12 months. for (int i = 0; i < 12; i++) { Console.WriteLine(now.ToString("MMM")); now = now.AddMonths(1); }Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Jan
In this example, we display the month string
in full. We need to specify four Ms next to each other in the format string
.
using System; DateTime now = DateTime.Now; for (int i = 0; i < 12; i++) { // Full month format. Console.WriteLine(now.ToString("MMMM")); now = now.AddMonths(1); }February March April May June July August September October November December January
We may want to have a 12-element array with all the month strings in it. This would allow us to access the month string
by its index (1 being equal to January).
static
array to cache strings is often faster than accessing them from the framework.The base class library provides powerful DateTime
methods. We do not need to manually type in month names in most cases. We can enumerate all the string
values.