如何在 C# 中将日期时间字符串转换为 DateTime

问题描述 投票:0回答:1

我有一个已经采用所需日期时间格式的字符串。我可以在 C# 中直接将其转换为 DateTime 吗?

我尝试了以下方法:

string datetimeFormat = "yyyy-MM-dd HH:mm:ss.fff";      
DateTime.ParseExact("2024-09-10 12:13:08.712", datetimeFormat, CultureInfo.InvariantCulture);
DateTime.ParseExact("2024-09-10 12:13:08.712", datetimeFormat, null);

我得到的这两个输出是不同的日期时间格式:

9/10/2024 12:13:08 下午

https://dotnetfiddle.net/CEOERT

c# datetime format
1个回答
2
投票

您得到不同输出的原因是

DateTime.ToString()
有一个默认格式,它将用于将
DateTime
转换为
string

您可以通过将格式传递给

.ToString()
来更改输出格式,例如:

string datetimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
            
DateTime dt1 = DateTime.ParseExact("2024-09-10 12:13:08.712", datetimeFormat, CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.ParseExact("2024-09-10 12:13:08.712", datetimeFormat, null);
            
Console.WriteLine(dt1.ToString(datetimeFormat));        
Console.WriteLine(dt2.ToString(datetimeFormat));

这将打印:

2024-09-10 12:13:08.712
2024-09-10 12:13:08.712
© www.soinside.com 2019 - 2024. All rights reserved.