CodeManiac CodeManiac - 4 years ago 118
C# Question

get only hour from datetime

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download