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

标签 c# timespan

当用户填写表格时,他们会使用下拉菜单来表示他们希望安排测试的时间。此下拉列表以 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/

相关文章:

c# - 检查集合中是否为 null

c# - 使用 WebClient 或类似方法从 .NET Framework 2.0 ASP.NET 应用程序获取 Azure AD 访问 token

c# - 处理和存储耗时

redis - Servicestack redis 客户端 : setting a key with timespan expiration fails using

c# - 什么是好的、免费的 C# 单元测试覆盖工具?

c# - 内存管理——C# VS Objective C?

c# - Sharepoint ClientObject 模型下载文件 C#

javascript - datejs TimeSpan 和 TimePeriod 问题

java - Java 中的 C# Timespan 等价物?

c# - 用年份格式化 TimeSpan