【发布时间】:2015-07-06 07:33:10
【问题描述】:
有很多方法可以确定给定日期的星期数或星期几。我想在我的应用程序中创建一个例程,在该月的最后一个星期五(可能等于也可能不等于本月最后一个完整周的这个星期五)执行一些例行的家务工作。
我想到了一些类似这些行的伪代码;
If AreWeOnTheFridayOfLastFullWeekOfTheMonth Then
<carry out housekeeping here>
End if
Private Function AreWeOnTheFridayOfLastFullWeekOfTheMonth
Dim dte As Date = Today
If dte.DayOfWeek.ToString = "Friday" Then
If <dte is in the last full week of the current month > then
Return True
Else
Return False
End
End Sub
有谁知道在各种 dot net 程序集中是否有这样的功能(我还没有在本月的第一周或最后一周的各种 google 或 bing 搜索中遇到过这种功能)或某种方式来确定它。
虽然我使用的是 vb,但答案是否在 c# 中并不重要,但明显的附带条件是它使用两种语言共有的函数和方法。
编辑
我看到了this 的问题。我想知道是否有一种更简单的方法可以简单地确定我们是否在本月的最后一周。
谢谢
编辑 2:
只是想我会添加 Jeppe Stig Nielsen 给出的上述两个简洁示例的 vb 翻译请注意,我已将 Today 替换为每种情况下的日期参数,这意味着您可以调用该函数并根据任何内容获得布尔返回是你叫它的日子。
Public Function TodayIsTheLastFridayOfTheLastFullWeekOfTheMonth() As Boolean
Dim daysLeftInMonth As Integer = DateTime.DaysInMonth(Today.Year, Today.Month) - Today.Day
Return Today.DayOfWeek = DayOfWeek.Friday AndAlso 8 > daysLeftInMonth AndAlso daysLeftInMonth >= 1
End Function
Public Function IsTodayWithinTheLastFullWeek() As Boolean
Dim dayOfWeekAsInt As Integer = CInt(Today.DayOfWeek) ' take more care here if 'first' day-of-week is not defined as Sunday
Dim dateOfBeginningOfWeek As Date = Today.AddDays(-dayOfWeekAsInt)
Dim daysLeftInMonth As Integer = DateTime.DaysInMonth(dateOfBeginningOfWeek.Year, dateOfBeginningOfWeek.Month) - dateOfBeginningOfWeek.Day
Return 13 > daysLeftInMonth AndAlso daysLeftInMonth >= 6
End Function
EDIT3
以及 Jeppe 对本月第一周的最终评论;
Public Function IsTodayWithinTheFirstFullWeek() As Boolean
Dim dayOfWeekAsInt As Integer = CInt(Today.DayOfWeek)
Dim dateOfBeginningOfWeek As Date = Today.AddDays(-dayOfWeekAsInt)
Return dateOfBeginningOfWeek.Day <= 7
End Function
【问题讨论】:
-
指定上一整周。如果最后一个星期五是在一个有 6 天的一周内怎么办?展示一些例子,包括边缘情况。
-
您认为一整周是周日到周六、周一到周日、周六到周五、周一到周五还是其他?
-
@TimSchmelter 如果我们以上周为例(我正在考虑从周日开始到周六结束的一周),它跨越了六月和七月。因此,如果我的伪函数在 6 月 26 日星期五被调用,它会返回 true,因为那将是本月的最后一周。
-
@DomSinclair 但是如果你想要一个月的最后一个星期五,你真的关心星期六是不是下个月的第一天吗?
-
"这可能等于也可能不等于本月最后一个完整周的这个星期五" 所以你不在乎它是否是最后一个完整的一周?