Encryption
Encryption

Reputation: 1897

TimeSpan conversion from Custom Strings

I've got a custom control on my page that has a field for Hours, Minutes, and AM/PM. I need to be able to take each string Hour + Minutes + AM/PM and get a valid TimeSpan so I can combine with a Date.

I've tried a couple different ways but get Invalid TimeSpan errors. Here is my code

 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);

Aside from considering errors with the Parse. How can I get a valid timespan from with the time strings and am/pm?

Thanks

Upvotes: 2

Views: 108

Answers (3)

pascalhein
pascalhein

Reputation: 5846

If you don't have to use TimeSpan, just parse the entire string with 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

Upvotes: 2

p.s.w.g
p.s.w.g

Reputation: 148980

TimeSpan objects don't have a concept of am / pm. You'd have to use a DateTime instead:

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

Further Reading

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564323

Just parse the DateTime once, at the end:

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);

There is no reason to build a TimeSpan in this case, as DateTime.Parse can handle dates with times as a single DateTime.

Upvotes: 3

Related Questions