如何获得给定月份的第一个、第二个或最后一个星期二(或一周中的任何一天) [英] How do I get first, second or last Tuesday (or any day of the week) of a given month
本文介绍了如何获得给定月份的第一个、第二个或最后一个星期二(或一周中的任何一天)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 VB.net 中寻找一个函数,该函数返回一个月中给定周的指定工作日的日期.类似于 Outlook 约会的内容.
I was looking for a function in VB.net that returns the date of the specified weekday of a given week in a month. Something similar to Outlook appointments.
例如:每个月的第一个星期一,每月第二个星期四或每月最后一个星期六
for example: First Monday of the month, Second Thursday of the month or Last Saturday of the month
我进行了搜索,但没有找到适合所有选项的通用工具.所以我创建了自己的并想分享它.
I searched but couldn't find anything versatile enough to all the options. So I created my own and would like to share it.
推荐答案
这是我的想法:
Public Function GetDate()
Dim dt As Date = Today
Dim FirstWeek As Integer = 1
Dim SecondWeek As Integer = 2
Dim ThirdWeek As Integer = 3
Dim FourthWeek As Integer = 4
Dim LastWeek As Integer = 5
MsgBox(GetNthDayOfNthWeek(dt, DayOfWeek.Monday, LastWeek).ToString)
End Function
Public Function GetNthDayOfNthWeek(ByVal dt As Date, ByVal DayofWeek As Integer, ByVal WhichWeek As Integer) As Date
'specify which day of which week of a month and this function will get the date
'this function uses the month and year of the date provided
'get first day of the given date
Dim dtFirst As Date = DateSerial(dt.Year, dt.Month, 1)
'get first DayOfWeek of the month
Dim dtRet As Date = dtFirst.AddDays(6 - dtFirst.AddDays(-(DayofWeek + 1)).DayOfWeek)
'get which week
dtRet = dtRet.AddDays((WhichWeek - 1) * 7)
'if day is past end of month then adjust backwards a week
If dtRet >= dtFirst.AddMonths(1) Then
dtRet = dtRet.AddDays(-7)
End If
'return
Return dtRet
End Function
享受吧!
这篇关于如何获得给定月份的第一个、第二个或最后一个星期二(或一周中的任何一天)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文