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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1226201/
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-08-06 13:54:50  来源:igfitidea点击:

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

c#vb.netdatetimevb6calendar

提问by

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. There is an ISO spec to do this but seems awfully complicated! 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)

我需要生成一份报告,显示一年中的 52 周(或某些年份的 53 周)及其开始和结束日期。有一个 ISO 规范可以做到这一点,但看起来非常复杂!我希望有人知道在 C# 或 Visual Basic 中执行此操作的方法(它实际上适用于 Visual Basic 6,但我会尝试将其移植)

回答by Paul van Brenk

use the Calendar.GetWeekOfYearmethod 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,它不是那么简单,你最好的办法是找到一个很好的库,它可以为你完成艰苦的工作。

回答by Max

If you want to do it manually, have a look at this post.

如果您想手动执行此操作,请查看此帖子

回答by Guffa

You can use the Calendar.GetWeekOfYearmethod to get the week number of a date, with the CalendarWeekRule.FirstFourDayWeekvalue to specify how the weeks are determined, and DayOfWeek.Mondayto specify the first weekday. That follows the ISO specification.

您可以使用该Calendar.GetWeekOfYear方法获取日期的周数,该CalendarWeekRule.FirstFourDayWeek值指定周的确定方式,并DayOfWeek.Monday指定第一个工作日。这遵循 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);

回答by Thorarin

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 mineuseful. It's barely documented, but it implements a few other operations on the WeekAndYear struct it defines. Plenty of room for improvement. Most notably, it defines <and >operators, but no others, which is pretty bad... but it should get you started.

你可能会发现我的这段代码很有用。它几乎没有记录,但它在它定义的 WeekAndYear 结构上实现了一些其他操作。有很大的改进空间。最值得注意的是,它定义了<>操作符,但没有其他的,这很糟糕……但它应该让你开始。

Porting to VB6 though... Hmm, maybe not :P

虽然移植到 VB6 ......嗯,也许不是:P

回答by Thorarin

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

回答by Garreth O Mahony

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 天

回答by ramon posadas

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