2

这是我的问题,我想以日期格式返回给定一周的星期一。

到目前为止,我在这里付出了努力。

代码:

Dim Diff
Dim cDate
Dim prday
prday = [table.datefield]
Diff = Cint(0 - (Weekday(prday, 2)))
cDate = DateAdd("d", Diff, prday)
Result = cDate

然而,这相当不幸地返回 24/12/1899。不完全是我想要的……2013 年会很好。关于我哪里出错的任何提示?

笔记:

从数据库表中提取的特定日期是在不同的应用程序中完成的。此代码应该生成将显示在标签上的日期。

4

2 回答 2

7

唯一的问题是你想如何对待周日约会。

'Sunday as first day of week
Dim someDate As DateTime = DateTime.Parse("Apr 28, 2013")
'calculate monday
'note:  for Sunday this returns next Monday, i.e Apr 28, 2013 returns Apr 29th
Dim monDate As DateTime = someDate.AddDays(DayOfWeek.Monday - someDate.DayOfWeek)

'Monday as first day of week
Dim someDate As DateTime = DateTime.Parse("Apr 28, 2013")
'calculate monday
If someDate.DayOfWeek = DayOfWeek.Sunday Then someDate = someDate.AddDays(-1)
Dim monDate As DateTime = someDate.AddDays(DayOfWeek.Monday - someDate.DayOfWeek)
于 2013-04-24T12:42:04.467 回答
2

定义扩展方法

Imports System.Runtime.CompilerServices

Module DateExtensions

    <Extension()> 
    Public Function GetMonday(ByVal dt As DateTime) as DateTime
        While dt.DayOfWeek <> DayOfWeek.Monday
           dt = dt.AddDays(-1)
        End While
        return dt
    End Function
End Module

并称它为

prday = prday.GetMonday()

或者我们可以让它通用

Public Function GetPreviousDayOfWeek(ByVal dt As DateTime, prevDay As DayOfWeek) as DateTime
    While dt.DayOfWeek <> prevDay
       dt = dt.AddDays(-1)
    End While
    return dt
End Function

正如@dbasnett 所指出的,数学比循环快,我们可以处理星期天是一周的第一天的情况。所以更好的方法应该是

Public Function GetMonday(ByVal dt As DateTime) as DateTime
    Dim diff = Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek - DayOfWeek.Monday
    dt = dt.AddDays(diff)
    return  dt.AddDays(DayOfWeek.Monday - dt.DayOfWeek)
End Function
于 2013-04-24T12:45:08.557 回答