📌  相关文章
📜  c# date to string yyyy-mm-dd - C# (1)

📅  最后修改于: 2023-12-03 15:29:45.463000             🧑  作者: Mango

C# Date to String yyyy-mm-dd

When working with dates in C#, it is often necessary to convert them to a string format. This can be achieved using the ToString() method and specifying a format string.

Converting DateTime to String yyyy-mm-dd Format

In order to convert a DateTime object to a string in yyyy-mm-dd format, we can use the following code:

DateTime date = DateTime.Now;
string dateString = date.ToString("yyyy-MM-dd");

The format string "yyyy-MM-dd" specifies that the output should be in yyyy-mm-dd format. The resulting string dateString will contain the date in this format.

Handling Null Dates

If the DateTime object is null, then attempting to call the ToString() method will result in a NullReferenceException. To handle this case, we can use the null-conditional operator ? to check if the object is null before attempting to convert it to a string:

DateTime? date = null;
string dateString = date?.ToString("yyyy-MM-dd");

If the date object is null, then the ToString() method will not be called and dateString will also be null.

Conclusion

Converting a DateTime object to a string in yyyy-mm-dd format is a common task when working with dates in C#. By using the ToString() method and a format string, we can easily achieve this. Be sure to handle null dates correctly by checking for null before conversion.