What is the method for formatting dates in C#?
In C#, the method to format dates is by using the ToString() method. This method can take a date format string as a parameter to specify the display format of the date.
Here are some common examples of date format strings:
- “d” is the short date format (e.g. 6/1/2022)
- “D” : Long date format (e.g. June 1, 2022)
- “t”: short time format (e.g. 10:30 AM)
- “T”: Long time format (e.g. 10:30:00 AM)
- “yyyy/MM/dd HH:mm:ss”: Custom date and time format (e.g. 2022/06/01 10:30:00)
Example of use:
DateTime now = DateTime.Now;
string shortDate = now.ToString("d");
string longDate = now.ToString("D");
string shortTime = now.ToString("t");
string longTime = now.ToString("T");
string customFormat = now.ToString("yyyy/MM/dd HH:mm:ss");
Please note that there is a difference between uppercase and lowercase letters in date format strings, which are used to specify different display formats.