开发者

calulate month from week no

i am getting week no开发者_如何学Python from database need to calculate which week of the month it is.

for ex:

week no = 7 month = 2

week no 11 month = 3

How to calculate it??

Just to add on i also have the year value with the week no.


Ok, I'll have a go, but it's not very pretty:

public int MonthOfWeek( int week, int year, CalendarWeekRule, weekrule, DayOfWeek firstDayOfWeek)
{
  GregorianCalendar gc = new GregorianCalendar();
  for( DateTime dt = new DateTime(year, 1, 1); dt.Year == year; dt = dt.AddDays(1))
  {
    if( gc.GetWeekOfYear( dt, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday) == week ){
      return dt.Month;
    }
  }
  return -1;
}  

This takes into consideration the culture specific rules for generating weeks. If a week is split between two months it will return the first month it encounters.

So in Norway, I would call this with CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday for correct results.


Calculate a date from weeknumber:

Calculate date from week number

Get the WeekOfMonth:

Calculate week of month in .NET


Assuming that you are looking for the month in the given year:

var dtYearStart = new DateTime(DateTime.Now.Year, 1, 1);
CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture;

// Check for the starting date of the initial week.
int diff = dtYearStart.DayOfWeek - defaultCultureInfo.DateTimeFormat.FirstDayOfWeek;
if (diff < 0)
{
 diff += 7;
}

dtYearStart = dtYearStart.AddDays(-1 * diff).Date;

int weekNo = 15;

DateTime dtWeekBased = dtYearStart.AddDays((weekNo-1) * 7);
string strMonth  = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dtWeekBased.Month);


Using DateTime, you can multiply week number by 7, get the total days passed on the year, add those days to 31/12/yyyy-1 and the get the month from the resulting DateTime.

I hope this to be useful to you.

See you.


4 week = 1 month so use

week%4

its return you no of month


Here a solution using the Time Period Library for .NET:

// ----------------------------------------------------------------------
public int GetMonthOfWeek( int weekOfYear )
{
  return new Week( weekOfYear ).FirstDayStart.Month;
} // GetMonthOfWeek
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜