Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Month ("M", "m") Format Specifier in C#
The Month ("M", "m") format specifier in C# represents a custom date and time format string that displays the month and day portions of a date. This format specifier is defined by the current DateTimeFormatInfo.MonthDayPattern property and typically follows the pattern MMMM dd.
Syntax
Following is the syntax for using the Month format specifier −
dateTime.ToString("M")
dateTime.ToString("m")
The custom format string pattern is −
MMMM dd
Using Month Format Specifier
Basic Example
using System;
using System.Globalization;
class Demo {
static void Main() {
DateTime date = new DateTime(2018, 6, 11, 9, 15, 0);
Console.WriteLine(date.ToString("m", CultureInfo.CreateSpecificCulture("en-us")));
Console.WriteLine(date.ToString("M", CultureInfo.CreateSpecificCulture("en-us")));
}
}
The output of the above code is −
June 11 June 11
Different Culture Formats
using System;
using System.Globalization;
class Demo {
static void Main() {
DateTime date = new DateTime(2023, 12, 25, 14, 30, 0);
Console.WriteLine("English (US): " + date.ToString("M", CultureInfo.CreateSpecificCulture("en-US")));
Console.WriteLine("French: " + date.ToString("M", CultureInfo.CreateSpecificCulture("fr-FR")));
Console.WriteLine("German: " + date.ToString("M", CultureInfo.CreateSpecificCulture("de-DE")));
Console.WriteLine("Current Culture: " + date.ToString("M"));
}
}
The output of the above code is −
English (US): December 25 French: 25 décembre German: 25. Dezember Current Culture: December 25
Comparison with Other Date Formats
| Format Specifier | Pattern | Example Output |
|---|---|---|
| "M" or "m" | MMMM dd | June 11 |
| "d" | M/d/yyyy | 6/11/2018 |
| "D" | dddd, MMMM dd, yyyy | Monday, June 11, 2018 |
| "Y" or "y" | MMMM yyyy | June 2018 |
Custom Pattern Access
using System;
using System.Globalization;
class Demo {
static void Main() {
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
Console.WriteLine("Month-Day Pattern: " + culture.DateTimeFormat.MonthDayPattern);
DateTime date = new DateTime(2023, 3, 8);
Console.WriteLine("Using 'M' specifier: " + date.ToString("M", culture));
Console.WriteLine("Using custom pattern: " + date.ToString(culture.DateTimeFormat.MonthDayPattern, culture));
}
}
The output of the above code is −
Month-Day Pattern: MMMM dd Using 'M' specifier: March 08 Using custom pattern: March 08
Conclusion
The Month format specifier ("M" or "m") in C# provides a culture-sensitive way to display month and day information. It automatically adapts to different locales and follows the MonthDayPattern defined in the current culture's DateTimeFormatInfo.
