如何用VB.NET在一周内找到星期一的日期?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (62)

我需要找到一种方法来查找我们所在星期一的星期一的日期(DD / MM / YYYY)。

例如,本周,星期一将是2009年11月9日,如果这是下周,它将是16/11/2009。

我设法得到了代码形式的地方,但我得到的只是'不能转换为Integer'错误。我使用Date.Today和AddDays()。

提问于
用户回答回答于

DateTime.DayOfWeek是一个枚举,指示给定日期的某一天。如星期一为1,您可以使用以下代码找到当前星期的星期一:

Dim monday As DateTime = Today.AddDays((Today.DayOfWeek - DayOfWeek.Monday) * -1)
用户回答回答于

如果星期日是一周的第一天,可以简单地这样做:

Dim today As Date = Date.Today
Dim dayDiff As Integer = today.DayOfWeek - DayOfWeek.Monday
Dim monday As Date = today.AddDays(-dayDiff)

如果星期一是星期的第一天:

Dim today As Date = Date.Today
Dim dayIndex As Integer = today.DayOfWeek
If dayIndex < DayOfWeek.Monday Then
    dayIndex += 7 'Monday is first day of week, no day of week should have a smaller index
End If
Dim dayDiff As Integer = dayIndex - DayOfWeek.Monday
Dim monday As Date = today.AddDays(-dayDiff)

扫码关注云+社区