将日历周转换为日期

时间:2011-01-20 12:32:42

标签: c# .net vb.net .net-4.0 calendar

是否有一个简单的内置函数可用于从日历周/年组合中获取日期实例?

应该可以将10w2005输入到TextBox中,然后从中创建日期07 March 2005

星期一应该是第一天,CalendarWeekRule应该是FirstFullWeek。

我的第一个方法是:

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

但这不起作用,因为FirstDay- CalendarWeekRule未应用。

提前致谢

修改

这就是我最终的结果(感谢fjdumont的链接):

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

2 个答案:

答案 0 :(得分:1)

This thread应该有所帮助。您将不得不解析字符串,有点像这样。

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

答案 1 :(得分: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)