How to round-off hours based on Minutes(hours+0 if min<30, hours+1 otherwise) ?
- by infant programmer
I need to round-off the hours based on the minutes in a DateTime variable. The condition is: if minutes are less than 30, then minutes must be set to zero and no changes to hours, else if minutes =30, then hours must be set to hours+1 and minutes are again set to zero. Seconds are ignored.
example:
11/08/2008 04:30:49 should become 11/08/2008 05:00:00
and 11/08/2008 04:29:49 should become 11/08/2008 04:00:00
I have written code which works perfectly fine, but just wanted to know a better method if could be written and also would appreciate alternative method(s).
string date1 = "11/08/2008 04:30:49";
DateTime startTime;
DateTime.TryParseExact(date1, "MM/dd/yyyy HH:mm:ss", null,
System.Globalization.DateTimeStyles.None, out startTime);
if (Convert.ToInt32((startTime.Minute.ToString())) > 29)
{
startTime = DateTime.Parse(string.Format("{0}/{1}/{2} {3}:{4}:{5}",
startTime.Month.ToString(), startTime.Day.ToString(),
startTime.Year.ToString(), startTime.Hour.ToString(), "00", "00"));
startTime = startTime.Add(TimeSpan.Parse("01:00:00"));
Console.WriteLine("startTime is :: {0}",
startTime.ToString("MM/dd/yyyy HH:mm:ss"));
}
else
{
startTime = DateTime.Parse(string.Format("{0}/{1}/{2} {3}:{4}:{5}",
startTime.Month.ToString(),
startTime.Day.ToString(), startTime.Year.ToString(),
startTime.Hour.ToString(), "00", "00"));
Console.WriteLine("startTime is :: {0}",
startTime.ToString("MM/dd/yyyy HH:mm:ss"));
}