简体   繁体   English

给出C#中的周数和年份,计算一周的开始和结束日期(基于ISO规范)

[英]Calculate the start and end date of a week given the week number and year in C# (based on the ISO specification)

I need to generate a report that shows the 52 weeks of a year (or 53 weeks as some years have) and their start and end dates. 我需要生成一份报告,显示一年中的52周(或某些年份为53周)及其开始和结束日期。 There is an ISO spec to do this but seems awfully complicated! 有一个ISO规范要做到这一点,但看起来非常复杂! Im hoping someone knows of a way to do it in C# or Visual Basic (its actually for Visual Basic 6 but I will try port it across) 我希望有人知道在C#或Visual Basic中实现它的方法(它实际上用于Visual Basic 6,但我会尝试将其移植到其中)

You can use the Calendar.GetWeekOfYear method to get the week number of a date, with the CalendarWeekRule.FirstFourDayWeek value to specify how the weeks are determined, and DayOfWeek.Monday to specify the first weekday. 您可以使用Calendar.GetWeekOfYear方法获取日期的周数,使用CalendarWeekRule.FirstFourDayWeek值指定周的确定方式,使用DayOfWeek.Monday指定第一个工作日。 That follows the ISO specification. 这符合ISO规范。

Example: 例:

int week = Calendar.GetWeekOfYear(DateTime.Today, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

To get the first date of the first week of the year, you can start from the 4th of january and go back until you find the monday: 要获得一年中第一周的第一个日期,您可以从1月4日开始,然后回到找到星期一:

DateTime t = new DateTime(DateTime.Today,Year, 1, 4);
while (t.DayOfWeek != DayOfWeek.Monday) t = t.AddDays(-1);

如果您想手动完成,请查看此帖子

This should work. 这应该工作。 I've used it on reporting in the past. 我过去曾在报道中使用它。 I agree that it's not very pretty though: 我同意它不是很漂亮:

DateTime GetWeekStartDate(int year, int week)
{
    DateTime jan1 = new DateTime(year, 1, 1);
    int day = (int)jan1.DayOfWeek - 1;
    int delta = (day < 4 ? -day : 7 - day) + 7 * (week - 1);

    return jan1.AddDays(delta);
}

That calculates the start date for a certain week. 这会计算某一周的开始日期。 The end DateTime is obviously 7 days later (exclusive). 结束日期时间显然是7天后(独家)。

You may find this code of mine useful. 您可能会发现我的这段代码很有用。 It's barely documented, but it implements a few other operations on the WeekAndYear struct it defines. 它几乎没有记录,但它在它定义的WeekAndYear结构上实现了一些其他操作。 Plenty of room for improvement. 有很大的改进空间。 Most notably, it defines < and > operators, but no others, which is pretty bad... but it should get you started. 最值得注意的是,它定义了<>运算符,但没有其他运算符,这非常糟糕......但它应该让你开始。

Porting to VB6 though... Hmm, maybe not :P 移植到VB6虽然...嗯,也许不是:P

These functions covered my requirements (adapted for ASP Classic, hence to data types) Hope they help others too... 这些功能涵盖了我的要求(适用于ASP Classic,因此适用于数据类型)希望他们也帮助其他人......

Function WeekNumber(dDate)
    Dim d2
    d2 = DateSerial(Year(dDate - WeekDay(dDate - 1) + 4), 1, 3)
    WeekNumber = Int((dDate - d2 + WeekDay(d2) + 5) / 7)
End Function

Function YearStart(iWhichYear)
    Dim iWeekDay
    Dim iNewYear
    iNewYear = DateSerial(iWhichYear, 1, 1)
    iWeekDay = (iNewYear - 2) Mod 7
    If iWeekDay < 4 Then
        YearStart = iNewYear - iWeekDay
    Else
        YearStart = iNewYear - iWeekDay + 7
    End If
End Function

Function WeeksInYear(iYear)
    WeeksInYear = WeekNumber(DateAdd("d", -1, YearStart(iYear + 1)))
End Function

Function WeekStart(iYear, iWeek)
    WeekStart = DateAdd("ww", iWeek - 1, YearStart(iYear))
End Function

Function WeekEnd(iYear, iWeek)
    WeekEnd = DateAdd("d", 6, DateAdd("ww", iWeek - 1, YearStart(iYear)))
End Function

use the Calendar.GetWeekOfYear method to get the week of the current datetime, the rest should be trivial. 使用Calendar.GetWeekOfYear方法获取当前日期时间的一周,其余的应该是微不足道的。

For vb6 it's less trivial, you're best bet is to find a good library which does the hard work for you. 对于vb6来说,它不那么简单,你最好的办法是找到一个能为你付出辛勤劳动的好图书馆。

This will give you the start of the current week 这将为您提供本周的开始

dateAdd(DateAdd(DateInterval.Day, (Now.Day * -1), Now)

To get the end of the week add 7 days to the start of the week 要在本周结束时添加7天到本周开始

the answer is the following and is the most understandable 答案如下,是最容易理解的

  '1 declaramos las variables Public firstdayweek As Date 'variable para capturar el valor de inicio de semana de una fecha dada Public lastdayweek As Date 'variable para el valor de la fecha final de una semana de una fecha dada Friend Property _NSemana As Integer 'indica el numero de la semana Friend Property _iniciosemana As Date 'contiene la primer fecha de la semana dada 'Fuciones para codigo 'Funcion para calcular la semana actual en la que estamos Function semana() As Date _NSemana = (DateDiff(DateInterval.WeekOfYear, DateTime.Today, New DateTime(DateTime.Today.Year, 1, 1)) *-1) End Function 'esta funcion es la que llamaremos para setear cada valor puedes colocarlo en cualquier evento Public Sub damerangosemana() semana() _iniciosemana = RangoSemana((_NSemana + 1), Today.Year) firstdayweek = _iniciosemana lastdayweek = FinSemana(_iniciosemana) End Sub 'con esta funcion capturamos el dia de la semana y asignamos la fecha incial Public Function RangoSemana(ByVal WeekNumber As Integer, ByVal year1 As Integer) As Date Dim numdia As Integer = 0 Dim oneDate As String Dim PrimerDia As Date oneDate = "1/1/" & year1.ToString PrimerDia = DateAndTime.DateValue(oneDate) 'dayOfYear = inDate.DayOfYear Select Case PrimerDia.DayOfWeek Case DayOfWeek.Sunday numdia = 7 Case DayOfWeek.Monday numdia = 1 Case DayOfWeek.Tuesday numdia = 2 Case DayOfWeek.Wednesday numdia = 3 Case DayOfWeek.Thursday numdia = 4 Case DayOfWeek.Friday numdia = 5 Case DayOfWeek.Saturday numdia = 6 End Select Dim x As Date = DateAdd(DateInterval.Day, 0 - numdia, CType(oneDate, Date)) Dim startdate As Date = DateAdd(DateInterval.WeekOfYear, WeekNumber - 1, x) Return startdate End Function 'funcion para calcular la fecha final Public Function FinSemana(ByVal Date1 As Date) As Date Return DateAdd(DateInterval.Day, 7, Date1) End Function 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM