Convert calendar-week to Date

江枫思渺然 提交于 2020-01-24 21:39:29

问题


is there a simple builtin function that i could use to get a date instance from a calendarweek/year-combination?

It should be possible to enter 10w2005 into a TextBox and i'll create the date 07 March 2005 from it.

Monday should be first day and CalendarWeekRule should be FirstFullWeek.

My first approach was:

Dim w As Int32 = 10
Dim y As Int32 = 2005
Dim d As New Date(y, 1, 1)
d = d.AddDays(7 * w)

But this does not work because the FirstDay- CalendarWeekRule are not applied.

Thanks in advance

Edit:

this is what i've ended with(Thanks to fjdumont for the link):

Public Shared Function FirstDateOfWeek(ByVal year As Integer, ByVal weekOfYear As Integer) As DateTime
      Dim jan1 As New DateTime(year, 1, 1)
      Dim daysOffset As Integer = CInt(Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek) - CInt(jan1.DayOfWeek)
      Dim firstWeekDay As DateTime = jan1.AddDays(daysOffset)
      Dim curCulture As System.Globalization.CultureInfo = System.Globalization.CultureInfo.CurrentCulture
      Dim firstWeek As Integer = curCulture.Calendar.GetWeekOfYear(jan1, curCulture.DateTimeFormat.CalendarWeekRule, curCulture.DateTimeFormat.FirstDayOfWeek)
      If firstWeek <= 1 Then
          weekOfYear -= 1
      End If
      Return firstWeekDay.AddDays(weekOfYear * 7)
End Function

回答1:


This thread should help. You will have to parse the string, somewhat like this.

string[] spl = input.ToLower().Split("w");
int year = int.Parse(spl[1]);
int week = int.Parse(spl[0]);



回答2:


    Dim dfi As Globalization.DateTimeFormatInfo = Globalization.DateTimeFormatInfo.CurrentInfo
    Dim cal As Globalization.Calendar = dfi.Calendar

    '10w2005
    Dim w As Integer = 10 'week
    Dim y As Integer = 2005
    Dim d As DateTime = New DateTime(y, 1, 1)

    If cal.GetWeekOfYear(d, Globalization.CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday) <> 1 Then
        w -= 1
        d = d.AddDays(8 - d.DayOfWeek)
    End If

    d = d.AddDays(7 * w)
    Debug.WriteLine(d.ToString)


来源:https://stackoverflow.com/questions/4747148/convert-calendar-week-to-date

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