使用 C# 将字符串转换为时间跨度?

Convert string into timespan using c#?

我需要将字符串转换为时间跨度,为此我使用了以下转换,

DateTime time = DateTime.ParseExact("12:00 AM", "h:mm tt", CultureInfo.InvariantCulture);
TimeSpan timeSpan = time .TimeOfDay;

除 12:00 AM 外,它对所有东西都有效,它为 AM/PM 提供 12:00,这对 12:00 PM 是可以的,但我需要 12:00 AM as 00:00:00,我有什么办法可以做到这一点吗?

使用下面的代码:

DateTime time = DateTime.ParseExact("00:00", "hh:mm", CultureInfo.InvariantCulture);

有关更多选项,请检查此 link

您不需要使用 ParseExact 而不是使用简单的 Parse 方法。但为了转换为时间,请为 ToString 方法使用 HH:mm 格式。

DateTime timeAM = DateTime.Parse("12:00 AM", CultureInfo.InvariantCulture);
DateTime timePM = DateTime.Parse("12:00 PM", CultureInfo.InvariantCulture);
Console.WriteLine(timeAM.ToString("HH:mm"));
Console.WriteLine(timePM.ToString("HH:mm"));

Returns 结果类似于:

//00:00
//12:00