当用户填写表格时,他们会使用下拉菜单来表示他们希望安排测试的时间。此下拉列表以 12 小时 AM/PM 形式包含一天中的所有时间,以 15 分钟为增量。因此,例如,如果用户选择下午 4:15,服务器将字符串 "4:15 PM"
发送到带有表单提交的网络服务器。
我需要了解如何将此字符串转换为时间跨度,以便将其存储在数据库的时间字段中(使用 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;
关于c# - 如何将 12 小时时间字符串转换为 C# TimeSpan?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661232/