示例#1
0
        /// <summary>
        /// Converts a timespan into a point in time on a given <paramref name="date" />.
        /// </summary>
        /// <param name="span">The span to add to the day.</param>
        /// <param name="date">The date on which the span should occur.</param>
        /// <returns>The time on the <paramref name="date" /> or the day after if the span is passed already.</returns>
        public static DateTimeOffset GetOffsetTimeByTimespan(this TimeSpan span, DateTimeOffset date)
        {
            var now     = DateTimeOffset.Now;
            var desired = date.BeginOfDay().Add(span);

            return(desired < now?date.AddDays(1).BeginOfDay().Add(span) : desired);
        }
        /// <summary>
        /// Retrieves the very first day of a year depending of the <see cref="CalendarWeekRule" /> of the given
        /// <paramref name="culture" />.
        /// </summary>
        /// <param name="year">The year to examine.</param>
        /// <param name="culture">The culture to use or <c>null</c> if <see cref="CultureInfo.CurrentUICulture" /> should be taken.</param>
        /// <param name="utcOffset">The optional offset to keep for the result.</param>
        /// <returns>The first day of the year.</returns>
        public static DateTimeOffset GetOffsetFirstDayOfYear(this int year, CultureInfo culture = null, TimeSpan utcOffset = default)
        {
            if (culture == null)
            {
                culture = CultureInfo.CurrentUICulture;
            }
            var startDate      = new DateTimeOffset(year, 1, 1, 0, 0, 0, utcOffset).AddDays(-10);
            var firstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;

            // find the start-day
            while (startDate.GetWeekNumber(culture) != 1)
            {
                startDate = startDate.AddDays(1);
            }
            // Go back to nearest start-date
            while (startDate.DayOfWeek != firstDayOfWeek)
            {
                startDate = startDate.AddDays(-1);
            }
            return(startDate.BeginOfDay());
        }