Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# .NET
Hi !
 
I am able to get Week No. of the Current Date (Code):
DateTime dt1 = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"));
int yyyy = dt1.Year; int MM = dt1.Month; int dd = dt1.Day;
        System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
        Int32 weekNo = ci.Calendar.GetWeekOfYear(new DateTime(yyyy, MM, dd), ci.DateTimeFormat.CalendarWeekRule, ci.DateTimeFormat.FirstDayOfWeek );
 
Now I want to get 1st Date from a Given Week No of the given Year.
Please suggest ...
Posted 14-Dec-12 22:26pm
Comments
arya.anu at 15-Dec-12 6:03am
   
The code correctly puts the start of week 1, 2009 at 29-12-2008. The CalendarWeekRule probably should be a parameter.
 
Note that the weekNum should be >= 1
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

static DateTime FirstDateOfWeek(int year, int weekNum, CalendarWeekRule rule)
{
    Debug.Assert(weekNum >= 1);
 
    DateTime jan1 = new DateTime(year, 1, 1);
 
    int daysOffset = DayOfWeek.Monday - jan1.DayOfWeek;
    DateTime firstMonday = jan1.AddDays(daysOffset);
    Debug.Assert(firstMonday.DayOfWeek == DayOfWeek.Monday);
 
    var cal = CultureInfo.CurrentCulture.Calendar;
    int firstWeek = cal.GetWeekOfYear(firstMonday, rule, DayOfWeek.Monday);
 
    if (firstWeek <= 1)
    {
        weekNum -= 1;
    }
 
    DateTime result = firstMonday.AddDays(weekNum * 7);
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Hi, I wrote it by hand but hope it'll help Smile | :)
public static DateTime GetYearWeekFirstDay(int year, int week)
{            
    var days = 7 * (week - 1) + 1;
 
    if (days > 366)
        throw new InvalidDataException("Invalid week numbers!");
 
    var date = new DateTime(year, 1, 1);
 
    if (date.DayOfWeek != DayOfWeek.Sunday)
        date = date.AddDays(7 - (int)(date.DayOfWeek));
 
    var count = 1;
 
    while (count != days)
    {
        count++;
        date = date.AddDays(1);
    }
 
    return date;
}
  Permalink  
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 340
1 OriginalGriff 210
2 DamithSL 170
3 Kornfeld Eliyahu Peter 130
4 Peter Leow 95
0 OriginalGriff 7,315
1 DamithSL 5,199
2 Sergey Alexandrovich Kryukov 4,917
3 Maciej Los 4,866
4 Kornfeld Eliyahu Peter 4,514


Advertise | Privacy | Mobile
Web04 | 2.8.141223.1 | Last Updated 15 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100