.Net get the current week is the week

Recent projects need to obtain the current week is the first few weeks of this year, something that sounds difficult, but quite interesting.

In China, a week from Monday began to count, ending Sunday, in a foreign country is not the case, is one week from Saturday to Sunday was.

There are many ways to achieve this function, here are two:

First, the use CultureInfo

In this way, only need to modify the parameters inside CultureInfo on the line, the United States is en-US, other countries to replace their own on the line.

It should be noted that, in many cases, the last week is the annual New Year's Eve, usually as the first week of next year to count, this was required by the business process.

public static int GetWeekNumOfTheYear(DateTime date)
        {
            CultureInfo myCI = new CultureInfo("zh-CN");
            Calendar myCal = myCI.Calendar;
            CalendarWeekRule myCWR = myCI.DateTimeFormat.CalendarWeekRule;
            DayOfWeek myFirstDOW = myCI.DateTimeFormat.FirstDayOfWeek;
            int weekOfYear = myCal.GetWeekOfYear(date, myCWR, myFirstDOW);
            return weekOfYear;
        }

 

Second, the use GregorianCalendar

This position may also obtain the current week are located in different regions, only need to modify GregorianCalendarTypes on the line, you can use GregorianCalendarTypes.Localized

public  static  int GetWeekNumOfTheYear1 (the DateTime DATE) 
{ 
    // Get the specified time is the first week of the year 
    the GregorianCalendar GC = new new the GregorianCalendar (GregorianCalendarTypes.USEnglish);
     int WeekOfYear = gc.GetWeekOfYear (DATE, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
     return WeekOfYear; 
}

Both methods in the System.Globalization namespace, it is quite easy to use.

Calls is also very simple, as follows, because the business needs, the annual New Year's Eve is the last week, the first week of next year as the need to count.

 public static string GetCurrentWeekNum(DateTime dt)
 {
      string result = string.Empty;
      var dt1 = GetWeekFirstDay(dt);
      var dt2 = GetWeekLastDay(dt);
      //Whether or not to cross the year
      if (dt1.Year == dt2.Year)
      {
          result = string.Format("{0} W {1}", dt1.Year, GetWeekNumOfTheYear(dt).ToString("00"));
      }
      else
      {
          result = string.Format("{0} W 01", dt2.Year);
      }
      return result;
  }

 

Guess you like

Origin www.cnblogs.com/bobo-pcb/p/11541800.html