Strip seconds from datetime

DateTime is actually stored separately as a Date and a TimeOfDay. We can easily re-initialize the date without including the seconds in the TimeSpan initialization. This also ensures any leftover milliseconds are removed.

date = date.Date + new TimeSpan(date.TimeOfDay.Hours, date.TimeOfDay.Minutes, 0);

You can create a new instance of date with the seconds set to 0.

DateTime a = DateTime.UtcNow;
DateTime b = new DateTime(a.Year, a.Month, a.Day, a.Hour, a.Minute, 0, a.Kind);

Console.WriteLine(a);
Console.WriteLine(b);

A simple solution which strips both seconds and milliseconds from a DateTime:

DateTime dt = DateTime.Now;
DateTime secondsStripped = dt.Date.AddHours(dt.Hour).AddMinutes(dt.Minute);

You can do

DateTime dt = DateTime.Now;
dt = dt.AddSeconds(-dt.Second);

to set the seconds to 0.

Tags:

C#