Friday, December 10, 2010

Rounding up (Ceiling) Days and Months in a DateTimeRange C#

This is something I required for billing reports and I struggled to find anything like it on the internet. So here it goes.

If you are pulling a report and you want to calculate a partial month as one month, this is how you would calculate it:

private Int32 GetMonthCountFromDateTimeRange(DateTimeRange oDateTimeRange)
        {
            DateTime endDate = oDateTimeRange.Stop ?? DateTime.Now;
            int numMonths = (endDate.Month - oDateTimeRange.Start.Value.Month) +
            (12 * (endDate.Year - oDateTimeRange.Start.Value.Year));
            TimeSpan tsDifference = endDate - oDateTimeRange.Start.Value;
            if (tsDifference.TotalDays > 0)
            {
                return numMonths + 1;
            }
            else
            {
                return numMonths;
            }
        }

If you are pulling a report and you want to calculate a partial day as one day, this is how you would calculate it

private Int32 GetDayCountFromDateTimeRange(DateTimeRange oDateTimeRange)
        {
            DateTime endDate = oDateTimeRange.Stop ?? DateTime.Now;
            TimeSpan tsDifference = endDate - oDateTimeRange.Start.Value;
           
            return Convert.ToInt32(Math.Ceiling(tsDifference.TotalDays));
        }

Hope this helps.

M

No comments:

Post a Comment