Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I have a variable; i.e. oDateTime with the type of DateTime & I extracted a time from it as follows:

C#
string.Format("{0:t}", oDateTime); 


Now my output is 4:00AM

My dropdownlist controls having the values like 01,02.....12 for Hours and 01,02...59 for Minutes & AM,PM for FormatDropdown control.

Now here on button click event it will retrieve the values & will show those values in controls as selected value as follows:

C#
ddlTFHrs.SelectedValue = String.Format("{0:hh}", oDateTime);

ddlTFMin.SelectedValue = String.Format("{0:mm}", oDateTime);

ddlTFAMPM.SelectedValue = String.Format("{0:tt}", oDateTime);


Here I am getting an error when I try to compare 04 with 4.

Can I format the time in string format as 04 or else is there any alternate way to compare these two values?

Thanks
Posted
Updated 11-Apr-12 5:57am
v2
Comments
sjelen 11-Apr-12 12:52pm    
String.Format("{0:hh}", oDateTime);
should format like 04.
Can you show how do you bind or populate dropdownlists?
Maybe text in dropdownlist items are '01', '02',... and values are '1', '2'?

1 solution

Don't convert it to a string - that is always a pain.
Instead, use http://msdn.microsoft.com/en-us/library/system.datetime.timeofday.aspx[^]
C#
TimeSpan timeOnly = DateTime.Now.TimeOfDay;

You can then compare this with your time of day directly.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 11-Apr-12 12:59pm    
My 5 just for the first sentence. Trying to work with string representation of data instead of data is one curse of the beginners.
--SA
sjelen 11-Apr-12 13:18pm    
True, but I think this is not the issue here. DropDownList.SelectedValue is a string, so he must convert whatever data type he uses to string in order to set selected item.
OriginalGriff 11-Apr-12 13:58pm    
No, you have the wrong idea entirely!
Never convert anything to a string to compare it: convert strings to math-friendly values, then compare them.
General rule of working with data: Convert from string as early as possible, Convert to string as late as possible.
And never do math on strings! :laugh:
sjelen 12-Apr-12 10:10am    
It's possible I got him wrong, but he did left out the code used for comparison. So I assumed the problem arose when he set SelectedValue and DropDownList must (internally) use string comparison against it's list of values to find selected item...
I completely agree with conversion rules, you already got mu +5 for that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900