如何将12小时时间字符串转换为C#TimeSpan?

当用户填写表单时,他们使用下拉列表表示他们希望安排测试的时间。 此下拉列表包含12小时上午/下午表格中15分钟增量的一天中的所有时间。 因此,例如,如果用户选择下午4:15,则服务器将字符串"4:15 PM"发送到具有表单提交的Web服务器。

我需要一些如何将此字符串转换为Timespan,因此我可以将其存储在我的数据库的时间字段中(使用linq to sql)。

有人知道将AM / PM时间字符串转换为时间跨度的好方法吗?

您可能希望使用DateTime而不是TimeSpan 。 您可以使用DateTime.ParseExact将字符串解析为DateTime对象。

 string s = "4:15 PM"; DateTime t = DateTime.ParseExact(s, "h:mm tt", CultureInfo.InvariantCulture); //if you really need a TimeSpan this will get the time elapsed since midnight: TimeSpan ts = t.TimeOfDay; 

最简单的方法是这样的:

 var time = "4:15 PM".ToTimeSpan(); 

这需要Phil的代码并将其放入辅助方法中。 这是微不足道的,但它使它成为一个单行电话:

 public static class TimeSpanHelper { public static TimeSpan ToTimeSpan(this string timeString) { var dt = DateTime.ParseExact(timeString, "h:mm tt", System.Globalization.CultureInfo.InvariantCulture); return dt.TimeOfDay; } } 

试试这个:

 DateTime time; if(DateTime.TryParse("4:15PM", out time)) { // time.TimeOfDay will get the time } else { // invalid time } 

我最喜欢Lee的答案,但如果你想使用tryparse,那么acermate就是正确的。 要结合它并获得时间跨度:

  public TimeSpan GetTimeFromString(string timeString) { DateTime dateWithTime = DateTime.MinValue; DateTime.TryParse(timeString, out dateWithTime); return dateWithTime.TimeOfDay; } 

尝试:

 string fromServer = (); var time = DateTime.Parse(fromServer); 

这会让你有时间,如果你创建了结束时间,你可以通过算术w / DateTime对象获得Timespans。