Click here to Skip to main content
15,885,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
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

C#
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);
 
Share this answer
 
v2
Hi, I wrote it by hand but hope it'll help :)
C#
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;
}
 
Share this answer
 
v3

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900