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

本文关键字:时间跨度 转换 字符串 使用 | 更新日期: 2023-09-27 18:03:33

我需要将字符串转换为时间跨度,为了实现这一点,我使用了以下转换,

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

这是工作良好的一切除了12:00 AM,它是给12:00 AM/PM,这是OK的12:00 PM,但我需要12:00 AM作为00:00:00,有什么办法,我可以实现这一点?

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

使用下面的代码:

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

更多选项请查看此链接

您不需要使用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"));

返回的结果类似于:

//00:00
//12:00