DateTime Extensions

Jan 12, 2012 at 1:05 AM
Edited Jan 12, 2012 at 1:06 AM

    /// <summary>
    /// Extensions of <see cref="System.DateTime"/>.
    /// </summary>
    public static class DateTimeExtensions
    {
        /// <summary>
        /// Gets the next weekday.
        /// </summary>
        /// <param name="start">The start.</param>
        /// <param name="day">The day.</param>
        /// <remarks>
        /// by Jon Skeet
        /// 
        /// For more detail, see:
        /// http://stackoverflow.com/questions/6346119/asp-net-get-the-next-tuesday
        /// </remarks>
        public static DateTime GetNextWeekday(this DateTime start, DayOfWeek day)
        {
            // The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
            int daysToAdd = ((int)day - (int)start.DayOfWeek + 7) % 7;
            return start.AddDays(daysToAdd);
        }
    }

Jan 12, 2012 at 1:07 AM

        [TestMethod]
        public void ShouldGetNextSaturday()
        {
            var now = DateTime.Now;
            var selectedDate = DateTime.Today.GetNextWeekday(DayOfWeek.Saturday);

            Assert.IsTrue(now.Day < selectedDate.Day, "The expected month day is not here.");
            Assert.IsTrue(selectedDate.DayOfWeek == DayOfWeek.Saturday, "The expected week day is not here.");
            Assert.IsTrue((selectedDate.Day - now.Day) < 7, "The expected day interval is not here.");
        }

        [TestMethod]
        public void ShouldGetStartAndEndDates()
        {
            var selectedDate = DateTime.Today.GetNextWeekday(DayOfWeek.Saturday);
            var days = (int)365/2;
            var startDate = selectedDate.AddDays(-days);
            var endDate = selectedDate.AddDays(days);

            Assert.IsTrue(endDate > startDate, "The expected greater End Date is not here.");
            Assert.IsTrue((endDate - startDate).Days == (days * 2), "The expected interval of days is not here.");
        }

        [TestMethod]
        public void ShouldSetBlackoutDates()
        {
            var selectedDate = DateTime.Today.GetNextWeekday(DayOfWeek.Saturday);
            var days = (int)365/2;
            var startDate = selectedDate.AddDays(-days);
            var endDate = selectedDate.AddDays(days);

            var blackoutDates = new ObservableCollection<CalendarDateRange>();

            var loopDate = startDate;
            while (loopDate <= endDate)
            {
                if (loopDate.DayOfWeek != DayOfWeek.Saturday)
                {
                    blackoutDates.Add(new CalendarDateRange(loopDate));
                }
                loopDate = loopDate.AddDays(1);
            }

            Assert.IsTrue(blackoutDates.Count > 0, "The expected blackout dates are not here.");
            Assert.IsTrue(blackoutDates.Where(i => i.Start.DayOfWeek == DayOfWeek.Saturday).Count() == 0, "The expected week days are not here.");
        }