C# DateTime Format: Quick Guide
In C#, you can use the ToString method of the DateTime class to convert time into a specific string format. Here are some common examples of time conversion.
- Convert the time to a specific date and time format.
DateTime now = DateTime.Now;
string formattedDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(formattedDateTime); // 输出示例:2021-01-01 12:30:45
- Convert time to a specific date format.
DateTime now = DateTime.Now;
string formattedDate = now.ToString("yyyy-MM-dd");
Console.WriteLine(formattedDate); // 输出示例:2021-01-01
- Convert time to a specific time format.
DateTime now = DateTime.Now;
string formattedTime = now.ToString("HH:mm:ss");
Console.WriteLine(formattedTime); // 输出示例:12:30:45
By passing different format strings into the ToString method, it is possible to convert time into strings in different formats. The specific format strings can be found in the DateTime.ToString method documentation in the .NET official documentation.