MS Access get ISO standard week number

不想你离开。 提交于 2021-02-05 06:51:48

问题


I'm surprised that I can't find any existing solutions to this online but I just need an SQL function that returns an ISO standard week number (i.e. the start of week 1 is always the first Monday of the year).

None of the DatePart function options consistently return the correct result. I had thought the option "vbFirstFourDays - Start with the first week that has at least four days in the new year." but testing it for today (12th Jan) returns week 3, not week 2 (my expression is DatePart("ww",Now(),2) )

This year ISO week 1 starts on 4th Jan, next Year the 2nd Jan and last year it was the 5th of Jan.

Many thanks


回答1:


The DatePart function does indeed calculate the ISO-8601 week number almost* correctly when it uses vbMonday for the firstdayofweek argument and vbFirstFourDays for the firstweekofyear argument, e.g.,

DatePart("ww", Date(), vbMonday, vbFirstFourDays)

or, when used directly in an Access query

DatePart("ww", Date(), 2, 2)

* Note that the bug documented here has apparently never been fixed, so the following Mondays in the 21st century are reported as being in week 53 when according to ISO-8601 they should be in week 1 of the following year:

2003-12-29
2007-12-31
2019-12-30
2031-12-29
2035-12-31
2047-12-30
2059-12-29
2063-12-31
2075-12-30
2087-12-29
2091-12-31




回答2:


Just to follow on from Gord Thompson, Microsoft have provided a workaround which returns the correct ISO week in all circumstances. It simply changes week 53 to week 1. Simply place this in a VBA Module and then you'll be able to use the function in Excel/Access.

Public Function ISOWeek(MyDate As Date) As Integer

      ISOWeek = Format(MyDate, "ww", vbMonday, vbFirstFourDays)
      If ISOWeek > 52 Then
         If Format(MyDate + 7, "ww", vbMonday, vbFirstFourDays) = 2 Then ISOWeek = 1
      End If

End Function


来源:https://stackoverflow.com/questions/34742007/ms-access-get-iso-standard-week-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!