在 .NET 中计算月份中的一周

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2136487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:50:21  来源:igfitidea点击:

Calculate week of month in .NET

.netdatetime

提问by eddiegroves

Do the .NET libraries have an easy way of returning the week number for a given date? For example, input of Year = 2010, Month = 1, Day = 25, should output 5for the week number.

.NET 库是否有一种简单的方法可以返回给定日期的周数?例如,输入Year = 2010, Month = 1, Day = 25, 应该输出5周数。

Closest I found was Calendar.GetWeekOfYear, which is almost there.

我发现的最近的是Calendar.GetWeekOfYear,几乎就在那里。

Java has a date string format "W" which returns week in month but I can't see anything equivalent in .NET.

Java 有一个日期字符串格式“W”,它按月返回一周,但我在 .NET 中看不到任何等效的东西。

回答by jason

There is no built in way to do this but here is an extension method that should do the job for you:

没有内置的方法可以做到这一点,但这里有一个扩展方法可以为您完成这项工作:

static class DateTimeExtensions {
    static GregorianCalendar _gc = new GregorianCalendar();
    public static int GetWeekOfMonth(this DateTime time) {
        DateTime first = new DateTime(time.Year, time.Month, 1);
        return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
    }

    static int GetWeekOfYear(this DateTime time) {
        return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
    }
}

Usage:

用法:

DateTime time = new DateTime(2010, 1, 25);
Console.WriteLine(time.GetWeekOfMonth());

Output:

输出:

5

You can alter GetWeekOfYearaccording to your needs.

您可以GetWeekOfYear根据自己的需要进行更改。

回答by Svish

There is no direct built-in way to do this, but it can be done quite easily. Here is an extension method which can be used to easily get the year-based week number of a date:

没有直接的内置方法可以做到这一点,但它可以很容易地完成。这是一个扩展方法,可用于轻松获取日期的基于年份的周数:

public static int GetWeekNumber(this DateTime date)
{
    return GetWeekNumber(date, CultureInfo.CurrentCulture);
}

public static int GetWeekNumber(this DateTime date, CultureInfo culture)
{
    return culture.Calendar.GetWeekOfYear(date,
        culture.DateTimeFormat.CalendarWeekRule,
        culture.DateTimeFormat.FirstDayOfWeek);
}

We can then use that to calculate the month-based week number, kind of like Jason shows. A culture friendly version could look something like this:

然后我们可以使用它来计算基于月份的周数,就像Jason 展示的那样。文化友好版本可能如下所示:

public static int GetWeekNumberOfMonth(this DateTime date)
{
    return GetWeekNumberOfMonth(date, CultureInfo.CurrentCulture);
}

public static int GetWeekNumberOfMonth(this DateTime date, CultureInfo culture)
{
    return date.GetWeekNumber(culture)
         - new DateTime(date.Year, date.Month, 1).GetWeekNumber(culture)
         + 1; // Or skip +1 if you want the first week to be 0.
}

回答by Jason Gilley

The title is misleading. The question is really about the calendar week number(the week number if you counted rows on a calendar) of the month, not the actual week number.

标题有误导性。问题实际上是关于月份的日历周数(如果您计算日历上的行数,则为周数),而不是实际的周数。

For the week number of the month, you can use:

对于一个月的周数,您可以使用:

VB:
    Function WeekNumber(TargetDate As Date) As Integer
        Return (TargetDate.Day - 1) \ 7 + 1
    End Function

C#:
    public int WeekNumber(DateTime TargetDate)
    {
        return (TargetDate.Day - 1) / 7 + 1;
    }

回答by GaussZ

As specified here: http://forums.asp.net/t/1268112.aspx

如此处指定:http: //forums.asp.net/t/1268112.aspx

you can use:

您可以使用:

public static int Iso8601WeekNumber(DateTime dt)
{
    return  CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

public static int GetWeekOfMonth(DateTime dt)
{    

    int weekOfYear = Iso8601WeekNumber(dt);

    if (dt.Month == 1)
    {
        //week of year == week of month in January
        //this also fixes the overflowing last December week
        return weekOfYear;
    }

    int weekOfYearAtFirst = Iso8601WeekNumber(dt.AddDays(1 - dt.Day));
    return weekOfYear - weekOfYearAtFirst + 1;
}

Note thought that your needs may vary as there are certain algorithmic choices. I.e. is a week with Monday-Friday at the end of February also the first week of March, or what criteria defines the "first" week of a month? ISO 8601:2004 does not give a definition for "Week of Month".

请注意,您的需求可能会有所不同,因为有某些算法选择。即是 2 月底的星期一至星期五也是 3 月的第一周的一周,或者什么标准定义了一个月的“第一”周?ISO 8601:2004 没有给出“月中的一周”的定义。

回答by Benjo

@Svish

@Svish

VB version:

VB版本:

Public Shared Function GetWeekNumber(ByVal [date] As DateTime) As Integer
    Return GetWeekNumber([date], CultureInfo.CurrentCulture)
End Function

Public Shared Function GetWeekNumber(ByVal [date] As DateTime, ByVal culture As CultureInfo) As Integer
    Return culture.Calendar.GetWeekOfYear([date], culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek)
End Function

Public Shared Function GetWeekNumberOfMonth(ByVal [date] As DateTime) As Integer
    Return GetWeekNumberOfMonth([date], CultureInfo.CurrentCulture)
End Function

Public Shared Function GetWeekNumberOfMonth(ByVal [date] As DateTime, ByVal culture As CultureInfo) As Integer
    Return GetWeekNumber([date], culture) - GetWeekNumber(New DateTime([date].Year, [date].Month, 1), culture) + 1
    ' Or skip +1 if you want the first week to be 0.
End Function

回答by ravula sandeep

This is my solution:

这是我的解决方案:

    static string GetWeekNumber()
    {

        var weekNumber = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek,
            DayOfWeek.Sunday) -
        CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now.AddDays(1 - DateTime.Now.Day),
            CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday) + 1;

        switch (weekNumber)
        {
            case 1 :
                return "First";
            case 2:
                return "Second";
            case 3:
                return "Third";
            default:
                return "Fourth";
        }
    }

回答by Glenn Ferrie

Here's a simple option if you want the first 7 days to be considered the first week, even if the month doesn't start on a Sunday:

如果您希望将前 7 天视为第一周,即使该月不是从星期日开始,这是一个简单的选项:

class Program
{
    static void Main(string[] args)
    {
        var dates = Enumerable.Range(0, 10)
            .Select(r => new DateTime(2015, 10, 1).AddDays(r))
            .Select(q => new { Date = q, WeekOfMonth = q.WeekOfMonth() });

        foreach(var item in dates)
        {
            Console.WriteLine("Date: {0:ddd MM-dd-yyyy}, WOM: {1}", item.Date, item.WeekOfMonth);
        }

        var final = Console.ReadLine();
    }
}

public static class DateTimeExtensions
{
    public static int WeekOfMonth(this DateTime d)
    {
        var isExact = (d.Day % 7 == 0);
        var offset = isExact ? 0 : 1;
        return (int)Math.Floor(d.Day / 7.0) + offset;
    }
}

回答by cazavientos

Once you have the DayOfWeek of the first day of month, you can get the week of month using integer arithmetic.

获得一个月第一天的 DayOfWeek 后,您可以使用整数算法获得一个月中的第几周。

static class DateTimeExtensions
{
    // Assumes that in current culture week starts on Sunday
    public static int GetWeekOfMonth(this DateTimeOffset time)
    {
        DateTimeOffset first = new DateTimeOffset(time.Year, time.Month, 1, 0, 0, 0, time.Offset);
        int firstSunday = (7 - (int)first.DayOfWeek) % 7 + 1;
        int weekOfMonth = 1 + (time.Day + 7 - firstSunday) / 7;

        return weekOfMonth;
    }
}

回答by ?zgür Kaplan

This is an old thread but I needed something like this and this is what I come up with.

这是一个旧线程,但我需要这样的东西,这就是我想出的。

public static int WeekOfMonth(this DateTime date)
{
    DateTime firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
    int firstDay = (int)firstDayOfMonth.DayOfWeek;
    if (firstDay == 0)
    {
        firstDay = 7;
    }
    double d = (firstDay + date.Day - 1) / 7.0;
    return (int)Math.Ceiling(d);
}

Note: This should work if you want to use Monday as the first day of the week. If you want the week to start on Sunday, this fails in 2nd week of March, 2015 and probably other dates. Monday March 9th, 2015 is the first day of the second week. The calculation above returns "3" for this date.

注意:如果您想将星期一用作一周的第一天,这应该可行。如果您希望一周从星期日开始,这将在 2015 年 3 月的第二周和其他日期失败。2015 年 3 月 9 日星期一是第二周的第一天。上面的计算为该日期返回“3”。

回答by Misi

public int WeekCalc(DateTime dt)
{
    CultureInfo ciCurr = CultureInfo.CurrentCulture;
    int weekNum = ciCurr.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    return weekNum;
}