Click here to Skip to main content
12,511,665 members (47,232 online)
Rate this:
 
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 21:26pm
Comments
arya.anu 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 :)
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
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160929.1 | Last Updated 15 Dec 2012
Copyright © CodeProject, 1999-2016
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