Post moved to new location:
http://code.mareoblo.pl/2008/12/15/c-get-the-first-date-of-week-for-specified-date/
15-12-2008 by Marek Śliwiński
Post moved to new location:
http://code.mareoblo.pl/2008/12/15/c-get-the-first-date-of-week-for-specified-date/
I think using a while is not the best option, this can be done easily just finding the difference:
DayOfWeek selDow = cultureInfo.Calendar.GetDayOfWeek(dayInWeek);
int diff = selDow – firstDay;
return dayInWeek.AddDays(-diff);
Hi Alex,
Thanks for valuable comment. Sure your proposal looks better also for me so I updated my post.
Greetz
Edit: 2009-03-04
Return to Joel code version (which is the only one correct which I know. Try to test 2009-02-01 date as Joel wrote in his comment below).
Thanx for this simple solution.
Greetz,
houthakker
Marek,
Please disregard my previous post as the code example was flawed.
I read your post with great interest and was starting to rewrite my own post. I did however recognize the above solution and realized that I had, at the time of writing my post, contemplated using it. The problem is however that in .NET sunday is enumerated as 0 and monday as 1 (as opposed to the ISO standard where monday should be 0). This means that if you do this with the above method:
DateTime date = new DateTime(2009, 2, 1);
CultureInfo culture = new CultureInfo(”sv-SE”);
DateTime firstDate = GetFirstDateOfWeek(date, culture);
firstDate will actually be 2009-02-02 as opposed to the correct 2009-01-26.
I’d love to find another solution than the while-loop but so far it’s the only one I’ve found that has always worked for me :/
Best regards,
/Joel
Joel,
Thanks for you comment which corrected my post edit in good manner! You are completely right. I tested a lot other solutions from the web forums, blogs etc. and all failed test with 2009-02-01 :)) I try my own to find better solution but I failed ;)
Thank you very much!
Greetings,
Marek
I think this will be much easier to find the first date of the week..
DayOfWeek today = DateTime.Now.DayOfWeek;
DateTime firstDate = DateTime.Now.AddDays(-(int)today);
Regrads,
Sarun P.T
Pala
Sarun,
Actually your piece of code is wrong. Please test it on 2009-02-01 date (1 feburary 2009). Good result should be 2009-01-26 (1st date of week for this test date).
Greetz,
Marek
I think this is a better answer. Works with 2009-02-01 too.
http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week
Thanks a lot for sharing this solution! Looks perfect :)