Reputation: 1014
how to extract only hour from date and time and convert it to integer so that I can compare to integer??
e.g.
datetime = 2013-02-01 10:24:36.000 i.e in the date and time data type
then
hour = take hour only i.e. 10
then
hour for comparision = Convert.ToInt32(time);
I have try this to item.StartTime which is date and time:
var time = String.Format("{HH}", (DateTime)item.StartTime);
var hour = Convert.ToInt32(time);
Error:
Input string was not in a correct format.
Upvotes: 3
Views: 11837
Reputation: 646
If you're looking to compare this with another date you might be able to save yourself a headache and just use DateTime.Compare
.
public static int Compare(
DateTime t1,
DateTime t2
)
http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx
Upvotes: 1
Reputation: 3451
How about this?
DateTime dt = DateTime.Now;
int hour = dt.Hour;
Its worth getting used to looking these things up in the MSDN documentation. It is pretty good once you get used to it. For a list of DateTime
members I just google System.DateTime and follow the top MSDN link (which is usually the first link).
http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Upvotes: 4
Reputation: 1500185
I think you're just looking for DateTime.Hour
:
int hour = item.StartTime.Hour;
... but it has a value of 10, not 24. (item.StartTime.Minute
would give you 24.)
As a rule of thumb, avoid string conversions unless they're an inherent part of what you're trying to accomplish.
Upvotes: 4