Reputation: 39
How to add below two drop-down hours as follows below:-
In my app I have a drop-down box of strings that shows possible hours in 12-hour time for the user to select
9am
9.30am
10am
10.30am
11am
11.30am
12pm
12.30pm
etc,
And another drop-down box of strings that shows possible hours like
1hour
2hour
3hour
etc
When user select first drop-down after that he/she select second drop-down then i want to add these values and select difference of hours like
if user select
first value=11.30pm
second value=2hours
then ,i want to show End Time=1.30AM
Upvotes: 2
Views: 705
Reputation: 460340
You can use a combination of DateTime.ParseExact
, int.Parse
, DateTime.AddHours
and DateTime.ToString
:
DateTime dt = DateTime.ParseExact("11.30am", "hh.mmtt", CultureInfo.InvariantCulture);
var digits = "2hours".TakeWhile(Char.IsDigit); // take only the first digit(s)
int hours = int.Parse(new string(digits.ToArray()));
String result = dt.AddHours(hours).ToString("h.mmtt", CultureInfo.InvariantCulture);
Result: 1.30PM
(so your desired result is incorrect because it's PM instead of AM)
In your case you have to handle the DropDownList
's SelectedIndexChanged
-events and use the SelectedValue
property. But you should use more maningful values in the ListItem
s anyway.
For example:
<asp:DropDownList id="DdlTime" runat="server"
OnSelectedIndexChanged="OnSelectedIndexChangedMethod">
<asp:ListItem value="690">
11.30am
</asp:ListItem>
etc....
</asp:DropDownList>
Here you can use TimeSpan.FromMinutes(int.Parse(ddlTime.SelectedValue))
to get the TimeSpan
or directly DateTime.Today.AddMinutes(int.Parse(ddlTime.SelectedValue))
.
Upvotes: 4