C# 将字符串转换为 DateTime 类型:安全可靠的 TryParse 方法
{"title":"C# 将字符串转换为 DateTime 类型:安全可靠的 TryParse 方法","description":"使用 C# 的 DateTime.TryParse 方法安全地将各种格式的字符串转换为 DateTime 类型,如果转换失败则返回 null。","keywords":"C#, DateTime, TryParse, 字符串转换, 日期时间, 安全转换","content":""使用 C# 的 DateTime.TryParse 方法安全地将各种格式的字符串转换为 DateTime 类型,如果转换失败则返回 null。"\n\n"以下是一个示例方法:"\n\ncsharp\npublic DateTime? ConvertToDateTime(string input)\n{\n DateTime result;\n if (DateTime.TryParse(input, out result))\n {\n return result;\n }\n else\n {\n return null;\n }\n}\n\n\n"这个方法将输入字符串尝试转换为 DateTime 类型。如果转换成功,则返回转换后的 DateTime 对象;如果无法转换,则返回 null。"\n\n"您可以根据需要修改此方法,例如添加其他格式的日期时间字符串支持。"\n\n"例如,您可以使用以下代码调用此方法:"\n\ncsharp\nstring input = \"2023-10-26\" ;\nDateTime? dateTime = ConvertToDateTime(input);\n\nif (dateTime.HasValue)\n{\n Console.WriteLine(dateTime.Value); // 输出 2023-10-26 00:00:00\n}\nelse\n{\n Console.WriteLine(\"无法转换\" );\n}\n\n\n"请注意,此方法仅支持常见的日期时间格式,如果您需要支持其他格式,则需要进行相应的修改。"
原文地址: https://www.cveoy.top/t/topic/qsst 著作权归作者所有。请勿转载和采集!