自定义字符串的TimeSpan转换

时间:2013-07-12 17:33:41

标签: c# datetime

我的页面上有一个自定义控件,其中包含“小时”,“分钟”和“上午/下午”字段。我需要能够获取每个字符串小时+分钟+上午/下午并获得有效的TimeSpan,以便我可以与日期结合。

我尝试了几种不同的方式,但得到了无效的TimeSpan错误。这是我的代码

 string date = DateDropDown.SelectedValue;
 string hour = HourDropDown.SelectedValue;
 string minute = MinuteDropDown.SelectedValue;
 string timeofDay = AMPMDropDown.SelectedValue;

 string timeStr = hour.PadLeft(2, '0') + ":" + minute + timeofDay;

 TimeSpan custTime = TimeSpan.Parse(timeStr);
 DateTime custDate = DateTime.Parse(date);
 DateTime callBackDT = custDate.Add(custTime);

除了考虑Parse的错误。如何从时间字符串和上午/下午获得有效的时间跨度?

由于

3 个答案:

答案 0 :(得分:3)

最后解析DateTime一次:

string date = DateDropDown.SelectedValue;
string hour = HourDropDown.SelectedValue;
string minute = MinuteDropDown.SelectedValue;
string timeofDay = AMPMDropDown.SelectedValue;

string dateStr = date + " " + hour.PadLeft(2, '0') + ":" + minute + " " + timeofDay;

DateTime callBackDT = DateTime.Parse(dateStr);

在这种情况下,没有理由构建TimeSpan,因为DateTime.Parse可以将时间作为单个DateTime处理。

答案 1 :(得分:2)

如果您不必使用TimeSpan,只需使用DateTime.Parse解析整个字符串:

var timeStr = string.Format("{0} {1}:{2} {3}", date, hour.PadLeft(2, '0'), minute, timeofDay);
var callBackDT = DateTime.Parse(timeStr, CultureInfo.CreateSpecificCulture("en-US"));
// Or whatever culture your string will be formatted with

答案 2 :(得分:1)

TimeSpan个对象没有am / pm的概念。您必须改为使用DateTime

string timeStr = hour.PadLeft(2, '0') + ":" + minute.PadLeft(2, '0') + " " + timeofDay;
DateTime custDate = DateTime.ParseExact("HH:mm t", timeStr, null);
TimeSpan custTime = custDate.TimeOfDay;

进一步阅读