CodeManiac
CodeManiac

Reputation: 1014

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.

Upvotes: 3

Views: 11837

Answers (4)

GirishBabuC
GirishBabuC

Reputation: 1379

//In Single line

int Time = DateTime.Now.Hour;

Upvotes: -1

GordonsBeard
GordonsBeard

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

Andrew Skirrow
Andrew Skirrow

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

Jon Skeet
Jon Skeet

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

Related Questions