format a date in to the format 'yyyy-mm-dd hh:mm:ss' in csharp

To format a date in C# into the yyyy-mm-dd hh:mm:ss format, you can use the ToString() method along with a custom format string. Here's an example:

main.cs
DateTime date = DateTime.Now; // example date
string formattedDate = date.ToString("yyyy-MM-dd HH:mm:ss"); // format the date

Console.WriteLine(formattedDate); // output: 2022-05-16 14:36:30
192 chars
5 lines

In the custom format string, yyyy represents the year with four digits, MM represents the month with two digits, dd represents the day with two digits, HH represents the hour in 24-hour format with two digits, mm represents the minute with two digits, and ss represents the seconds with two digits.

Note that the HH format specifier is used instead of hh, which represents the hour in 12-hour format.

gistlibby LogSnag