datetime format string in csharp

In C#, you can format a DateTime object to string using the ToString() method with a format string. The format string consists of format specifiers that define how different parts of the date and time should be represented in the string.

Here is an example that demonstrates various ways to format a DateTime object:

main.cs
DateTime now = DateTime.Now;

// Format the date and time in the default format
string defaultFormat = now.ToString();
Console.WriteLine(defaultFormat);  // Output: 10/5/2022 2:30:45 PM

// Format the date in a custom format
string customFormat = now.ToString("MM/dd/yyyy");
Console.WriteLine(customFormat);   // Output: 10/05/2022

// Format the time in a custom format
string timeFormat = now.ToString("hh:mm:ss tt");
Console.WriteLine(timeFormat);     // Output: 02:30:45 PM

// Combine date and time in a custom format
string combinedFormat = now.ToString("MM/dd/yyyy hh:mm:ss tt");
Console.WriteLine(combinedFormat); // Output: 10/05/2022 02:30:45 PM
656 chars
18 lines

In the example above, "MM/dd/yyyy" represents the month (two digits), followed by the day (two digits), followed by the year (four digits). "hh:mm:ss tt" represents the hour (two digits 12-hour clock), followed by the minute (two digits), followed by the second (two digits), followed by the AM/PM designator.

You can find more information on the available format specifiers in the official documentation: Custom date and time format strings.

related categories

gistlibby LogSnag