在.NET中计算一周中的星期几

时间:2010-01-25 23:26:20

标签: .net datetime

.NET库是否可以轻松返回给定日期的周数?例如,Year = 2010, Month = 1, Day = 25的输入应输出周数的5

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

Java有一个日期字符串格式“W”,它每个月都会返回,但我在.NET中看不到任何相同的内容。

13 个答案:

答案 0 :(得分:56)

没有内置的方法可以做到这一点,但这里有一个扩展方法,应该为你做的工作:

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);
    }
}

用法:

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

输出:

5

您可以根据需要更改GetWeekOfYear

答案 1 :(得分:19)

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

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);
}

然后,我们可以使用它来计算基于月份的周数,类似于Jason shows。文化友好版可能看起来像这样:

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.
}

答案 2 :(得分:12)

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

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

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;
    }

答案 3 :(得分:4)

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

你可以使用:

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;
}

请注意,由于存在某些算法选择,您的需求可能会有所不同。即是一周,周二到周五,也就是2月底的第一周,或者是什么标准定义了一个月的“第一”周? ISO 8601:2004没有给出“月周”的定义。

答案 4 :(得分:2)

@Svish

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

答案 5 :(得分:2)

这是我的解决方案:

    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";
        }
    }

答案 6 :(得分:1)

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

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);
}

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

答案 7 :(得分:1)

如果您希望将前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;
    }
}

答案 8 :(得分:0)

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

答案 9 :(得分:0)

一旦你有了月初一天的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;
    }
}

答案 10 :(得分:0)

简单......:)

private int WeeksNumber()
        {
            int daysInMonth = DateTime.DaysInMonth(YourYear, YourMonth);
            DateTime date = new DateTime(Year, Month, 1);
            switch (daysInMonth)
            {
                case 28:
                    {
                        if (date.DayOfWeek == DayOfWeek.Monday)
                        {
                            return 4;
                        }
                        else
                        {
                            return 5;
                        }
                    }
                case 29:
                    {
                        return 5;
                    }
                case 30:
                    {
                        if (date.DayOfWeek == DayOfWeek.Sunday)
                        {
                            return 6;
                        }
                        else
                        {
                            return 5;
                        }
                    }
                case 31:
                    {
                        if (date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday)
                        {
                            return 6;
                        }
                        else
                        {
                            return 5;
                        }
                    }
                default: return 5;
            }
        } 

答案 11 :(得分:0)

$response = Requests::get($link,
        array(
            'Accept'=>'application/json',
            'Accept-Charset'=>'utf-8',
            "Connection"=> "keep-alive",
        ),array('timeout'=>0));

答案 12 :(得分:0)

为什么不像此扩展程序那么简单?

public static int WeekNumber( this DateTime d )
{
    int w = 0;

    if ( d.Day <= 7 )
    {
        w = 1;
    }
    else if ( d.Day > 7 && d.Day <= 14 )
    {
        w = 2;
    }
    else if ( d.Day > 14 && d.Day <= 21 )
    {
        w = 3;
    }
    else if ( d.Day > 21 && d.Day <= 28 )
    {
        w = 4;
    }
    else if ( d.Day > 28 )
    {
        w = 5;
    }

    return w;
}