c# - 获取月份的第几周 C#

标签 c# winforms datetime week-number

<分区>

我想使用 C# 桌面应用程序查找现在在周数上的日期。

我一直在谷歌上寻找,但没有一个符合我的需要。

如何获得一个月中的一周,如下例所示?

示例:

我想要 2014 年 1 月 6 日 = 1 月的第一周

2014 年 1 月 30 日 = 一月的第四个

但 2014 年 2 月 1 日 = 1 月的第 4 周

2014 年 2 月 3 日是二月的第一周

最佳答案

方法如下:

static int GetWeekNumberOfMonth(DateTime date)
{
    date = date.Date;
    DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
    DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
    if (firstMonthMonday > date)
    {
        firstMonthDay = firstMonthDay.AddMonths(-1);
        firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
    }
    return (date - firstMonthMonday).Days / 7 + 1;
}

测试:

Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 6)));  // 1
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 30))); // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 1)));  // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 3)));  // 1

关于c# - 获取月份的第几周 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23060121/

相关文章:

c# - 在不重新启动应用程序的情况下应用更新

php - 返回的 php DateTime 有什么问题?

c# - 如果提交了错误的凭据,程序将抛出错误

c# - Caliburn Micro IoC/DI 工厂方法

c# - 如何将暴露给 COM 互操作的 .NET 对象标记为单线程?

c# - 如何在C#中截取滚动窗口的屏幕截图

c# - 如何在 C# 中手动调用事件?

java - 如何在 Java 中解析 UTC 日期/时间

Javascript 日期循环丢失 2015 年 2 月

c# - 命名管道可以执行我想做的事吗?