format a date in to the format month day, year in csharp

To format a date to the format "month day, year" in C#, you can use the DateTime.ToString() method with a custom date and time format string. Here's an example:

main.cs
DateTime date = DateTime.Now;
string formattedDate = date.ToString("MMMM dd, yyyy");
Console.WriteLine(formattedDate); // Output: e.g. "October 29, 2021"
154 chars
4 lines

In the above code, we first create a DateTime object for the current date and time using the DateTime.Now property. We then call the ToString() method on this object and pass in a custom date and time format string "MMMM dd, yyyy".

The "MMMM" specifier represents the full name of the month, "dd" represents the zero-padded day of the month, and "yyyy" represents the four-digit year.

The resulting string is stored in the formattedDate variable and printed to the console using the Console.WriteLine() method.

gistlibby LogSnag