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

You can use the DateTime.ToString() method to format a DateTime object as a string in the desired format. Here's an example:

main.cs
DateTime now = DateTime.Now;
string formattedDate = now.ToString("yyyy-MM-dd HH:mm:ss.fff");
Console.WriteLine(formattedDate); // Output: "2022-03-14 13:42:17.123"
164 chars
4 lines

In the format string "yyyy-MM-dd HH:mm:ss.fff", the yyyy specifies the year (four digits), MM specifies the month (two digits), dd specifies the day (two digits), HH specifies the hour in 24-hour format (two digits), mm specifies the minute (two digits), ss specifies the second (two digits), and fff specifies the millisecond (three digits).

Note that the capital HH is used to specify the hour in 24-hour format. If you want to use 12-hour format instead, use the lowercase hh instead. You can also customize the formatting by using different format specifiers or by specifying a custom format string.

Also, note that the culture of the system could affect how the date is displayed. You can specify a culture by using the CultureInfo parameter in the ToString() method.

gistlibby LogSnag