3

我正在尝试获取本周星期一的日期。这接近正确吗?

Dim MondayOfCurrentWeek As Date = Date.Today - Date.Today.DayOfWeek + 1

据我了解,AyOfWeek 索引是:

1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday
0 = Sunday

因此,如果例如今天的日期是星期四,我会得到:

Dim MondayOfCurrentWeek As Date = Date - 4 + 1 

这将等于

Date - 3

对我来说似乎是正确的。

还是我完全不在了?

4

5 回答 5

6

一种非常简单的替代方法,虽然性能可能不高,但确实避免了任何基于算术的错误:

Dim monday As Date = Date.Today
While (monday.DayOfWeek <> DayOfWeek.Monday)
    monday = monday.AddDays(-1)
End While

这可以很容易地扩展到处理一周中任何一天的功能。除非这是一段非常大量的代码,否则性能会很好。

于 2015-01-12T11:05:44.930 回答
3

这应该做你想要的。它从提供的日期查找前一个星期一。没有循环,因此会很快并且不依赖枚举值进行算术调整,因此如果枚举值发生变化也不会中断:

Public Shared Function PreviousMonday(ByVal dateValue As DateTime) As DateTime
    Dim dayOffset As Integer
    Select Case dateValue.DayOfWeek
        Case DayOfWeek.Sunday : dayOffset = 6
        Case DayOfWeek.Monday : dayOffset = 0
        Case DayOfWeek.Tuesday : dayOffset = 1
        Case DayOfWeek.Wednesday : dayOffset = 2
        Case DayOfWeek.Thursday : dayOffset = 3
        Case DayOfWeek.Friday : dayOffset = 4
        Case DayOfWeek.Saturday : dayOffset = 5
    End Select

    Return dateValue.AddDays(-1 * dayOffset)
End Function
于 2015-01-12T14:56:22.173 回答
0

如果您正在寻找前一周的星期一到星期日的范围,那么您可以使用这些函数来获取它们(修改版来自 Matt Wilko 的答案)。

Public Shared Function PreviousMonday(ByVal dateValue As Date) As Date
Dim dayOffset As Integer
Select Case dateValue.DayOfWeek
    Case DayOfWeek.Sunday : dayOffset = -13
    Case DayOfWeek.Monday : dayOffset = -7
    Case DayOfWeek.Tuesday : dayOffset = -8
    Case DayOfWeek.Wednesday : dayOffset = -9
    Case DayOfWeek.Thursday : dayOffset = -10
    Case DayOfWeek.Friday : dayOffset = -11
    Case DayOfWeek.Saturday : dayOffset = -12
End Select

Return dateValue.AddDays(dayOffset)
End Function

Public Shared Function PreviousSunday(ByVal dateValue As Date) As Date
Dim dayOffset As Integer
Select Case dateValue.DayOfWeek
    Case DayOfWeek.Sunday : dayOffset = -7
    Case DayOfWeek.Monday : dayOffset = -1
    Case DayOfWeek.Tuesday : dayOffset = -2
    Case DayOfWeek.Wednesday : dayOffset = -3
    Case DayOfWeek.Thursday : dayOffset = -4
    Case DayOfWeek.Friday : dayOffset = -5
    Case DayOfWeek.Saturday : dayOffset = -6
End Select

Return dateValue.AddDays(dayOffset)
End Function
于 2020-06-23T10:11:06.283 回答
0
var now = DateTime.Now; //17.09.2020 19:15:49
int dayInWeek = (int)now.DayOfWeek; //4
var previousMonday = now.AddDays(-(((dayInWeek + 6) % 7) + 7)); //-10
var previousSunday= previousMonday.AddDays(6); //-4
        
Console.WriteLine(previousMonday); //07.09.2020 19:15:49
Console.WriteLine(previousSunday); //13.09.2020 19:15:49
于 2020-09-17T17:18:42.740 回答
-1
Enumerable.Range(0,7).Select(Function(r) Date.Now.AddDays(-1*r).Date).
Where(Function(r) r.DayOfWeek = DayOfWeek.Monday).FirstOrDefault()
于 2022-01-20T20:36:36.813 回答