gpt4 book ai didi

c# - 在 C# 中将字符串解析为 DateTime

转载 作者:IT王子 更新时间:2023-10-29 03:31:36 26 4
gpt4 key购买 nike

我的日期和时间格式如下:

"2011-03-21 13:26" //year-month-day hour:minute

如何将它解析为 System.DateTime

如果可能的话,我想使用像 DateTime.Parse()DateTime.ParseExact() 这样的函数,以便能够手动指定日期的格式。

最佳答案

DateTime.Parse() 会尝试找出给定日期的格式,通常效果很好。如果您可以保证日期始终采用给定格式,那么您可以使用 ParseExact():

string s = "2011-03-21 13:26";

DateTime dt =
DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

(但请注意,在日期不符合预期格式的情况下,使用其中一种 TryParse 方法通常更安全)

确保检查 Custom Date and Time Format Strings在构造格式字符串时,尤其要注意字母的数量和大小写(即“MM”和“mm”的含义截然不同)。

C# 格式字符串的另一个有用资源是 String Formatting in C#

关于c# - 在 C# 中将字符串解析为 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5366285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com