Finding Week, using current date ? In C#?

Go To StackoverFlow.com

0

In C# how can i find the week of the current date, i am trying to get the week number of the current date, can you help me, thank you.

2012-04-04 05:31
by Surya sasidhar


3

See Calendar.GetWeekOfYear

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
      DateTime date1 = new DateTime(2011, 1, 1);
      Calendar cal = dfi.Calendar;

      Console.WriteLine("{0:d}: Week {1} ({2})", date1, 
                        cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, 
                                          dfi.FirstDayOfWeek),
                        cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));       
   }
}
// The example displays the following output:
//       1/1/2011: Week 1 (GregorianCalendar)
2012-04-04 05:34
by ColinE
Note that if you want ISO8601-compatible weeks, this won't match up. You need to use something like this: http://blogs.msdn.com/b/shawnste/archive/2006/01/24/iso-8601-week-of-year-format-in-microsoft-net.asp - porges 2012-04-04 05:41
ya thank you, Mr. ColinE it is wroking fine, but i want to get the current month week [current date], can you help me. In the current month current date week, week1 week2... week 5 like tha - Surya sasidhar 2012-04-04 05:57


0

If you need current week "global" number, you can use this:

using System;
using System.Globalization;    

DateTime date = DateTime.Now;
int res = 0;

// First day of year
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

// (Default) First four day week from Sunday
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday);

// First four day week from StartOfWeek
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

// First full week from Sunday
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);

// First full week from StartOfWeek
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek); 

If you need week number in a month, use smth like such code:

 DateTime beginningOfMonth = DateTime.Now;

 while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
     date = date.AddDays(1);

 int result = (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;
2012-04-04 07:07
by thezar
Ads