format a date in to the format month day, year hour:minute:second am/pm in csharp

To format a DateTime object to the format "month day, year hour:minute:second am/pm", you can use the ToString() method with a custom format string:

main.cs
DateTime dt = DateTime.Now;
string formattedDate = dt.ToString("MMMM d, yyyy h:mm:ss tt");
Console.WriteLine(formattedDate); // Output: "January 1, 2022 1:23:45 PM"
165 chars
4 lines

Here, "MMMM d, yyyy h:mm:ss tt" is the custom format string that specifies the desired format. Here's what each part of the format string means:

  • MMMM: The full name of the month (e.g. "January").
  • d: The day of the month as a number (without leading zeros).
  • ,: A literal comma character (to separate the month and day).
  • yyyy: The year as a four-digit number.
  • h: The hour as a number (12-hour clock).
  • :: A literal colon character (to separate the minutes and seconds).
  • mm: The minutes as a number (with leading zeros).
  • ss: The seconds as a number (with leading zeros).
  • tt: The AM/PM designator (e.g. "AM" or "PM").

You can customize the format string as per your requirement.

gistlibby LogSnag