查询计算日历日

时间:2011-11-15 05:07:50

标签: c#

我们可以使用日历规则同时获取公历中的日期,就像我们一年中的一周 - GetWeekInYear(日期时间日期,日历规则,DayOfweek firstDayOfWeek)?

2 个答案:

答案 0 :(得分:2)

使用GregorianCalendar.GetDayOfYear(DateTime time)

我不知道计算当天的任何文化差异的规则。

<强>更新

如果您想计算从一年中第一周的第一天开始计算的天数,根据特定CalendarWeekRule确定一年中的第一周,您可以执行以下操作(说明作为GregorianCalendar类的扩展方法:

public static class GregorianCalendarExtensions
{
    private const int DaysInWeek = 7;

    public static int GetDaysFromStartOfFirstWeekOfYear(
        this GregorianCalendar calendar,
        DateTime time,
        CalendarWeekRule rule,
        DayOfWeek firstDayOfWeek)
    {
        DayOfWeek dayOfWeek = calendar.GetDayOfWeek(time);

        // Calculate 0-index day of week relative to first day of week.
        int completedDaysInWeek =
            ((int)dayOfWeek + DaysInWeek - (int)firstDayOfWeek) % DaysInWeek;

        // Decrement week of year by 1 to give count of completed weeks.
        int completedWeeksInYear =
            calendar.GetWeekOfYear(time, rule, firstDayOfWeek) - 1;

        // Increment by one to start counting from 1 rather than 0.
        return (completedWeeksInYear * DaysInWeek) + completedDaysInWeek + 1;
    }
}

使用示例:

        GregorianCalendar cal = new GregorianCalendar();
        DateTime jan01;
        DateTime.TryParse("1/1/2011", out jan01);
        for (int i = 0; i < 4; i++)
        {
            DateTime date = jan01 + TimeSpan.FromDays(i);

            Console.WriteLine(
                "{2} {0} is day {1} of year.",
                date.ToShortDateString(),
                cal.GetDaysFromStartOfFirstWeekOfYear(
                    date,
                    CalendarWeekRule.FirstFullWeek,
                    DayOfWeek.Sunday),
                cal.GetDayOfWeek(date));
        }

答案 1 :(得分:0)

使用Calendar类?快速检查MSDN文档似乎意味着它没有一种方法可以直接提供您想要的内容。

但是,通过将Calendar类与DateTime类相结合,可以编写一个尽可能多的方法。