Mona Coder
Mona Coder

Reputation: 6316

How to get date of a day in a week in C#

I am trying to get Date of a specific day based on its sequence in a week like

 GetDate(22, 4);

which needs to return the date of 4th day in 22nd weeks of current year. How can I do this?

void Main()
{
    int months;
    var year = DateTime.Now.ToString("yyyy");
    months = GetWeeksInYear( Convert.ToInt32(year));
    Console.WriteLine(months);
}

public int GetWeeksInYear(int year)
{
      DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
      DateTime date1 = new DateTime(year, 12, 31);
      Calendar cal = dfi.Calendar;
      return  cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);    
}

public int GetDate(int weekNo, int dayNo)
{
  return // Date
}

Upvotes: 0

Views: 201

Answers (3)

firstable the week of the year is a calendar calculation and locale dependent value so you have to consider that when giving the week number... So you are for sure missing the use of something like

CultureInfo.CurrentCulture.Calendar;

Upvotes: 0

Nemo
Nemo

Reputation: 3373

I think a simple way would be to take Jan 1 of year and add number of days,

DateTime day = new DateTime(year, 1, 1).AddDays((week * 7) + days);

Upvotes: 0

itsme86
itsme86

Reputation: 19486

You can just add the number of days from the beginning of the year:

var dt = new DateTime(year, 1, 1);
dt = dt.AddDays(weekNo * 7 + dayNo);
var date = dt.Date;

Upvotes: 3

Related Questions