format a date in to the format october 13, 2014 11:13:00 am in csharp

To format a date in the mentioned format, we can use the ToString method of the DateTime object and pass the appropriate format string. Here's an example:

main.cs
DateTime date = new DateTime(2014, 10, 13, 11, 13, 00);
string formattedDate = date.ToString("MMMM dd, yyyy hh:mm:ss tt");
Console.WriteLine(formattedDate); // Output: October 13, 2014 11:13:00 AM
197 chars
4 lines

In the format string,

  • "MMMM" represents the full month name
  • "dd" represents the day of the month with leading zeros
  • "yyyy" represents the year with four digits
  • "hh" represents the hour in 12-hour format with leading zeros
  • "mm" represents the minutes with leading zeros
  • "ss" represents the seconds with leading zeros
  • "tt" represents the AM/PM designator

By passing this format string, we can get the desired output.

gistlibby LogSnag