简体   繁体   中英

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
}

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;

我认为一种简单的方法是采用每年的1月1日加上天数,

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

每年的第一个星期是日历计算和与语言环境相关的值,因此在提供星期数时您必须考虑到这一点...因此,您肯定会漏掉类似

CultureInfo.CurrentCulture.Calendar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM