DantheMan
DantheMan

Reputation: 7417

Getting only hour/minute of datetime

Using C#, I have a datetime object, but all I want is the hour and the minutes from it in a datetime object.

So for example: if I have a DateTime object of July 1 2012 12:01:02 All I want is July 1 2012 12:01:00 in the datetime object (so, no seconds).

Upvotes: 58

Views: 258346

Answers (4)

Sid
Sid

Reputation: 791

Try this:

String hourMinute = DateTime.Now.ToString("HH:mm");

Now you will get the time in hour:minute format.

Upvotes: 79

Ribtoks
Ribtoks

Reputation: 6922

Just use Hour and Minute properties

var date = DateTime.Now;
date.Hour;
date.Minute;

Or you can easily zero the seconds using

var zeroSecondDate = date.AddSeconds(-date.Second);

Upvotes: 38

NominSim
NominSim

Reputation: 8511

I would recommend keeping the object you have, and just utilizing the properties that you want, rather than removing the resolution you already have.

If you want to print it in a certain format you may want to look at this...That way you can preserve your resolution further down the line.

That being said you can create a new DateTime object using only the properties you want as @romkyns has in his answer.

Upvotes: 2

Roman Starkov
Roman Starkov

Reputation: 61382

Try this:

var src = DateTime.Now;
var hm = new DateTime(src.Year, src.Month, src.Day, src.Hour, src.Minute, 0);

Upvotes: 72

Related Questions