I want to strip/remove seconds from a DateTime. Starting with a full Datetime like:
DateTime datetime = DateTime.UtcNow;
I want to strip the seconds using any inbuilt function or regular expression.
Input: 08/02/2015 09:22:45
Expected result: 08/02/2015 09:22:00
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);
You can do
DateTime dt = DateTime.Now;
dt = dt.AddSeconds(-dt.Second);
to set the seconds to 0.
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);