如何使用 vb.net 根据周数获取一周的开始日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20084890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:53:46  来源:igfitidea点击:

How to get starting date in a Week based on week number using vb.net?

vb.net

提问by J-J

I need help on getting the starting date of a week from a given week number in vb.net.

我需要帮助从 vb.net 中的给定周数获取一周的开始日期。

I have combobox binded with items 1-53 as week numbers. What I want to do is whenever I select a specific week number, it will return the first date of that selected week number.

我将组合框与项目 1-53 绑定为周数。我想要做的是每当我选择特定的周数时,它都会返回所选周数的第一个日期。

For instance I have selected week Number 46, it must return November 11, 2013 as first date of week number 46.

例如,我选择了第 46 周,它必须返回 2013 年 11 月 11 日作为第 46 周的第一个日期。

I have tried the following codes and it returns only the first date of a week from a current week number.

我尝试了以下代码,它仅从当前周数返回一周的第一个日期。

DateAdd("d", -Weekday(Now, FirstDayOfWeek.Monday) + 1, Now)

Is there any possible way that can return my expected output?

有什么可能的方法可以返回我的预期输出吗?

Please help me. Thanks in advance.

请帮我。提前致谢。

采纳答案by vbigham

You could try something like this:

你可以尝试这样的事情:

Private Sub TestDateAdd()
    Dim weekStart As DateTime = GetWeekStartDate(46, 2013)
    Console.WriteLine(weekStart)
End Sub


Private Function GetWeekStartDate(weekNumber As Integer, year As Integer) As Date
    Dim startDate As New DateTime(year, 1, 1)
    Dim weekDate As DateTime = DateAdd(DateInterval.WeekOfYear, weekNumber - 1, startDate)
    Return DateAdd(DateInterval.Day, (-weekDate.DayOfWeek) + 1, weekDate)
End Function

Disclaimer: I only really tested this with the one input, you probably want to make sure that it works as expected for different years, etc..

免责声明:我只真正用一个输入测试过这个,你可能想确保它在不同的年份都能按预期工作,等等。

回答by Jike

Public Function FirstDateOfWeek(ByVal Year As Integer, ByVal Week As Integer, Optional FirstDayOfWeek As DayOfWeek = DayOfWeek.Monday) As Date
    Dim dt As Date = New Date(Year, 1, 1)
    If dt.DayOfWeek > 4 Then dt = dt.AddDays(7 - dt.DayOfWeek) Else dt = dt.AddDays(-dt.DayOfWeek)
    dt = dt.AddDays(FirstDayOfWeek)
    Return dt.AddDays(7 * (Week - 1))
End Function