如何转换12个小时的时间字符串转换成C#的时间跨度? [英] How do I convert a 12 hour time string into a C# TimeSpan?

查看:139
本文介绍了如何转换12个小时的时间字符串转换成C#的时间跨度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户填写表单,他们使用一个下拉表示,他们想安排用于测试的时间。此下拉包含在12小时AM / PM表格15分钟为增量一天的所有时间。因此,例如,如果用户选择下午4:15,服务器发送字符串4:15 PM与形式submittion的网络服务器。

When a user fills out a form, they use a dropdown to denote what time they would like to schedule the test for. This drop down contains of all times of the day in 15 minute increments in the 12 hour AM/PM form. So for example, if the user selects 4:15 pm, the server sends the string "4:15 PM" to the webserver with the form submittion.

我需要一些如何这个字符串转换成时间跨度,所以我可以(与LINQ to SQL中)存储在我的数据库的时间字段。

I need to some how convert this string into a Timespan, so I can store it in my database's time field (with linq to sql).

任何人都知道的一个AM / PM时间字符串转换为时间跨度的好办法?

Anyone know of a good way to convert an AM/PM time string into a timespan?

推荐答案

您可能需要使用一个的DateTime 而不是时间跨度的。您可以使用 DateTime.ParseExact 来解析字符串转换成一个DateTime对象。

You probably want to use a DateTime instead of TimeSpan. You can use DateTime.ParseExact to parse the string into a DateTime object.

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;

这篇关于如何转换12个小时的时间字符串转换成C#的时间跨度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆