Jimbo
Jimbo

Reputation:

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

Upvotes: 4

Views: 23853

Answers (8)

ramon posadas
ramon posadas

Reputation: 1

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


  
  

Upvotes: 0

Garreth O Mahony
Garreth O Mahony

Reputation: 11

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

Upvotes: 1

Jimbo
Jimbo

Reputation:

These functions covered my requirements (adapted for ASP Classic, hence to data types) Hope they help others too...

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

Upvotes: 2

Thorarin
Thorarin

Reputation: 48476

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

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. 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

Upvotes: 2

Guffa
Guffa

Reputation: 700192

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. That follows the ISO specification.

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:

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

Upvotes: 5

Max
Max

Reputation: 2571

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

Upvotes: 2

Paul van Brenk
Paul van Brenk

Reputation: 7549

use the Calendar.GetWeekOfYear method to get the week of the current datetime, the rest should be trivial.

For vb6 it's less trivial, you're best bet is to find a good library which does the hard work for you.

Upvotes: 1

Related Questions