3

I can get week number if I use normal way like that. As you know this one calculates week number according to normal start date which is 01.01.2015.

CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(mydate, CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)

But I want to change that start date. For instance my first week of year will be 01.07.2015 and according to that date I want to calculate week of year for given date.

Kadir
  • 3,094
  • 4
  • 37
  • 57
  • Maybe take a look at Noda Time http://nodatime.org/ . And you should be aware that there is an international standard for how to number weeks. If you're considering inventing your own standard then you will cause confusion for anyone using the international standard. – RenniePet Jun 29 '15 at 22:31

4 Answers4

2

Substract a difference between new year and your start date from the mydate object

var startDate = new DateTime(2015, 7, 1);
var newYear = new DateTime(2015, 1, 1);

var culture = CultureInfo.CurrentCulture;
var weekOfYear = culture.Calendar.GetWeekOfYear(
    mydate.Add(newYear - startDate),
    culture.DateTimeFormat.CalendarWeekRule,
    culture.DateTimeFormat.FirstDayOfWeek);
hazzik
  • 13,019
  • 9
  • 47
  • 86
  • If you apply your code with startDate=Sunday 2015 Nov 1st & mydate=Wednesday 2015 Nov 4th, mydate.Add(newYear - startDate) gives Sunday 2015 january 4th. Then weekOfYear will be 2, whilst 1 was expected. – Graffito Jul 01 '15 at 11:26
  • @Graffito I'm getting "1st week"; It depends on your CalendarWeekRule and FirstDayOfWeek – hazzik Jul 01 '15 at 21:18
  • Hazzik: give me the rules (CalendarWeekRule and FirstDayOfWeek) you used for your code, and I will send dates where the returned result is incorrect. – Graffito Jul 01 '15 at 21:32
0

Maybe you could calculate the week number for your start date (e.g 01.07.2015 - 27) and then what is the week number for the actual date - e.g 12.12.2015 (50), and then just subtract - in this case 23?

jjczopek
  • 3,319
  • 2
  • 32
  • 72
-1

Just subtract the number of days between your wished week-1 date and the default start date and use that offset each time you calculate (.AddDays(offset)).

Wolf5
  • 16,600
  • 12
  • 59
  • 58
  • Dunno why this was downvoted. It explains something that works but doesn't show the code. Hazziks answer is the implementation of my description... – Wolf5 Jun 29 '15 at 23:30
-1

That way :

DateTime startDateTime = new DateTime(2015,07,01) ;
int fisrtDayOfWeek = 0 ; // 0:sunday for US, 1:Monday for many other coutries
DateTime week1StartDateTime = startDateTime ; 
for (int i=1;i<6;i++) if ((int)startDateTime.AddDays(i).Day==fisrtDayOfWeek )
  week1StartDateTime = startDateTime.AddDays(i) ;

int weekNumber= mydate<week1StartDateTime ? 1 :
    ((int)(mydate-week1StartDateTime).TotalDays)/7+1 ;
// note : casting double to int provides the floor (not round)
Graffito
  • 1,658
  • 1
  • 11
  • 10