[c#] 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).

This question is related to c#

The answer is


Try this:

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

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


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);

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.