开发者

Convert calendar-week to Date

开发者 https://www.devze.com 2023-02-05 23:14 出处:网络
is there a simple builtin function that i could use to get a date instance from a calendarweek/year-combination?

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开发者_如何学JAVA -= 1
      End If
      Return firstWeekDay.AddDays(weekOfYear * 7)
End Function


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]);


    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)
0

精彩评论

暂无评论...
验证码 换一张
取 消