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

Kal*_*exx 14 c# timespan

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

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

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

Phi*_*amb 38

您可能想要使用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;
Run Code Online (Sandbox Code Playgroud)

  • 此示例实际上不适用于"11:00 PM"等字符串.大写"H"格式表示24小时制.使用小写的"h"修复了这个问题. (7认同)

whi*_*and 7

最简单的方法是这样的:

var time = "4:15 PM".ToTimeSpan();
Run Code Online (Sandbox Code Playgroud)

.

这需要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;
    }
}
Run Code Online (Sandbox Code Playgroud)