如何获取给定周的第一天的日期?

时间:2016-11-08 14:15:16

标签: vbscript

假设:

weekNumber = 45, 
year = 2016

第一周的条件:

  • 从星期一开始

  • vbFirstFourDays - 从新年至少四天的一周开始

如何使用给定数据获取日期'Monday 07.11.2016' (dd.mm.yyyy)

3 个答案:

答案 0 :(得分:2)

由于接受的答案仍有错误的结果我在这里进行比较。

Option Explicit
Dim year, wn, wd, wk, Jan4, wdn, wno, nDay, Out

wn = 45

For year = 2012 to 2018
  Wscript.Echo "LotPings : " & ShowDate(DateYWkWd(year,wn,1)) 
  Wscript.Echo "Lankymart: " & Showdate(Lankymart(year,wn))
  Wscript.Echo "duDE     : " & Showdate(     duDE(year,wn))
  Wscript.Echo
Next

Function DateYWkWd(year, wn, wd)
  ' returns date based von VbMondeay and vbFirstFourDays
  Jan4 = Dateserial(year,1,4) ' garantied to be in first week
  DateYWkWd = DateAdd("ww",wn-1, DateAdd("d",wd-Weekday(Jan4,2),Jan4))
end Function

Function Lankymart(year, wn)
  wd = DateAdd("ww", wn, DateSerial(year,1,1))
  Lankymart = wd - WeekDay(wd, vbMonday) + 1
end Function

Function duDE(year, wn)
  nDay = 4 + (wn - 1)*7 - 1
  duDE = DateAdd("d", nDay, DateSerial(year,1,1))
end Function

Function ShowDate(date)
  Wd  = Weekday(date,vbMonday)
  Wdn = WeekDayName(Wd, True,vbMonday)
  Wno = datepart("ww", date, vbMonday, vbFirstFourDays)
  Out = Wdn & " " & date & " WeekNo : " & Wno
  If Wno <> wn Then Out = Out & " **wrong week **"
  If Wd  <> 1  Then Out = Out & " **wrong wkday**"
  ShowDate = Out
end Function

这里输出。功能DateYWkWd可以普遍使用 提供年,周数和星期几(1 =周一...... 7 =太阳)

LotPings : Mon 11/5/2012 WeekNo : 45
Lankymart: Mon 11/5/2012 WeekNo : 45
duDE     : Wed 11/7/2012 WeekNo : 45 **wrong wkday**

LotPings : Mon 11/4/2013 WeekNo : 45
Lankymart: Mon 11/11/2013 WeekNo : 46 **wrong week **
duDE     : Fri 11/8/2013 WeekNo : 45 **wrong wkday**

LotPings : Mon 11/3/2014 WeekNo : 45
Lankymart: Mon 11/10/2014 WeekNo : 46 **wrong week **
duDE     : Sat 11/8/2014 WeekNo : 45 **wrong wkday**

LotPings : Mon 11/2/2015 WeekNo : 45
Lankymart: Mon 11/9/2015 WeekNo : 46 **wrong week **
duDE     : Sun 11/8/2015 WeekNo : 45 **wrong wkday**

LotPings : Mon 11/7/2016 WeekNo : 45
Lankymart: Mon 11/7/2016 WeekNo : 45
duDE     : Mon 11/7/2016 WeekNo : 45

LotPings : Mon 11/6/2017 WeekNo : 45
Lankymart: Mon 11/6/2017 WeekNo : 45
duDE     : Wed 11/8/2017 WeekNo : 45 **wrong wkday**

LotPings : Mon 11/5/2018 WeekNo : 45
Lankymart: Mon 11/12/2018 WeekNo : 46 **wrong week **
duDE     : Thu 11/8/2018 WeekNo : 45 **wrong wkday**

答案 1 :(得分:1)

这可以通过DateAdd()WeekDay()功能的组合来完成,而无需执行手动计算。

Dim year: year = 2016
Dim wn: wn = 45
Dim wd: wd = DateAdd("ww", wn, DateSerial(year,1,1))

WScript.Echo wd - WeekDay(wd, vbMonday) + 1

输出:

07/11/2016

<强>更新

在5分钟内将它们放在一起,并且只需要最少的测试即可,但在某些年份,@lotpings answer proves仍会失败。这只是一个快速的刺,他们的答案肯定是正确的使用方法。

答案 2 :(得分:0)

所以你可以通过

获得一天
4 + (45 - 1)*7 - 1 = 311

因为第一周只有4天,剩下的44周有7天。

现在您可以通过DateAdd获取日期:

Dim nDay
nDay = 4 + (45 - 1)*7 - 1

Dim NewDate
NewDate = DateAdd("d", nDay, DateSerial(2016,1,1))

MsgBox NewDate