ASP.NET C# - Week Number

I use this to get the number of the month:
TimeCurrent.ToString("M")

Using C# and ASP.NET, how can I get the number of the week?  For example, the result for January 4 should be "1" and the result for December 30 should be "52".
LVL 10
skijAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SANTABABYCommented:
Try:
System.Globalization.GregorianCalendar Cal;

                Cal.GetWeekOfYear(......)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Miguel OzSoftware EngineerCommented:
Just to elaborate SANTABABY answer. Calendar.GetWeekOfYear  method is good for most practical purposes, but it depends on the week rule and the day of week evaluated, you must be careful to match them to your client culture.
For example, .NET does not support ISO 8601 week standard and it may fail to provide the correct info around end/start of the year as shown here.
0
David Johnson, CD, MVPOwnerCommented:
using System;
using System.Globalization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime Mydate, Mydate2, Mydate3;
            int Myweek, Myweek2, Myweek3;
            DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
            Calendar cal = dfi.Calendar;
            Mydate = DateTime.Now;
            Mydate2 = new DateTime(2015, 01, 01);
            Mydate3 = new DateTime(2015, 12, 25);
            CalendarWeekRule weekRule = CalendarWeekRule.FirstFourDayWeek;
            DayOfWeek firstWeekDay = DayOfWeek.Monday;
            Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
            Myweek = calendar.GetWeekOfYear(Mydate, weekRule, firstWeekDay);
            Myweek2 = calendar.GetWeekOfYear(Mydate2, weekRule, firstWeekDay);
            Myweek3 = calendar.GetWeekOfYear(Mydate3, weekRule, firstWeekDay);
            Console.WriteLine("{0}: Week {1}", Mydate.ToShortDateString(), Myweek.ToString());
            Console.WriteLine("{0}: Week {1}", Mydate2.ToShortDateString(), Myweek2.ToString());
            Console.WriteLine("{0}: Week {1}", Mydate3.ToShortDateString(), Myweek3.ToString());
            Console.ReadLine();
            }
    }
}

Open in new window


Note: 2015 Dec 31 is on Week 53
you might want to look at http://blogs.msdn.com/b/shawnste/archive/2006/01/24/iso-8601-week-of-year-format-in-microsoft-net.aspx
0
Gustav BrockCIOCommented:
You should use an extension method for this as shown below.

First, include an AddWeeks method which can be useful in many other situations.
Then you can calculate the ISO 8601very easily just by adding a week (study in-line comments).

Now,  include "using DateTimeExtension;" and you are set for this simple syntax:

    int yearOFWeek;
    int weekNumber =  someDate.WeekIso8601(out yearOfWeek);

or, if only the week number is useful:

    int weekNumber =  someDate.WeekIso8601();

 - as in this demo:
using System;
using DateTimeExtension;

namespace WeekDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int n = 0; n < 20; n++)
            {
                int year = 1996;
                int yearOfWeek;
                int weekNumber;
                DateTime lastDate = new DateTime(year + n, 12, 31);
                DateTime nextDate = lastDate.AddDays(1);
                weekNumber = lastDate.WeekIso8601(out yearOfWeek);
                Console.Write("{0} Week: {1}W{2} - ", lastDate.ToString("yyyy-MM-dd"), yearOfWeek.ToString(), weekNumber.ToString("00"));
                weekNumber = nextDate.WeekIso8601(out yearOfWeek);
                Console.WriteLine("{0} Week: {1}W{2}", nextDate.ToString("yyyy-MM-dd"), yearOfWeek.ToString(), weekNumber.ToString("00"));
            }
	    Console.ReadKey();	
        }
    }
}

Open in new window


Extension methods:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace DateTimeExtension
{
    /// <summary>
    /// Extended methods for System.DateTime.
    /// </summary>
    public static class DateTimeExtensionMethods
    {

        /// <summary>
        /// Minimum and maximum week number according to ISO 8601.
        /// </summary>
        private static int _minIso8601WeekNumber = 1;
        private static int _maxIso8601WeekNumber = 53;

        #region AddWeeks
        /// <summary>
        /// Returns a new System.DateTime that adds the specified number of weeks to the value of this instance.
        /// </summary>
        /// <param name="currentDate">The current date</param>
        /// <param name="weeks">A number of whole weeks. The value parameter can be negative or positive.</param>
        /// <returns>The date and time of this instance added the number of weeks.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        public static DateTime AddWeeks(this DateTime currentDate, int weeks)
        {
            CultureInfo cultureInfo = CultureInfo.InvariantCulture;
            Calendar calendar = cultureInfo.Calendar;
            return calendar.AddWeeks(currentDate, weeks);
        }

        #endregion

        #region WeekIso8601
        /// <summary>
        /// Gets the week number according to the ISO 8601 standard of this instance.
        /// <para>This is the corrected value from Calendar.GetWeekOfYear(this, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)</para>
        /// </summary>
        /// <param name="currentDate">The current date</param>
        /// <returns>Returns the ISO 8601 week number of this instance.</returns>
        public static int WeekIso8601(this DateTime currentDate)
        {
            CultureInfo cultureInfo = CultureInfo.InvariantCulture;
            Calendar calendar = cultureInfo.Calendar;
            CalendarWeekRule calenderWeekRule = CalendarWeekRule.FirstFourDayWeek;
            DayOfWeek firstDayOfWeek = DayOfWeek.Monday;

            int weekNumber = calendar.GetWeekOfYear(currentDate, calenderWeekRule, firstDayOfWeek);
            if (weekNumber.Equals(_maxIso8601WeekNumber))
            {
                // The week number appears to be 53. 
                // If so, the week number of the next week must be 1.
                // Obtain the week number of the next week and check if this is 1.
                int weekNumberNext = calendar.GetWeekOfYear(currentDate.AddWeeks(1), calenderWeekRule, firstDayOfWeek);
                if (!weekNumberNext.Equals(_minIso8601WeekNumber))
                {
                    // The next week has week number 2.
                    // Thus, the current week number is not 53 but 1.
                    weekNumber = _minIso8601WeekNumber;
                }
            }
            return weekNumber;
        }
        /// <summary>
        /// Gets the week number and year according to the ISO 8601 standard of this instance.
        /// <para>This is the corrected value from Calendar.GetWeekOfYear(this, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)</para>
        /// </summary>
        /// <param name="currentDate">The current date</param>
        /// <param name="yearOfWeek">The year of the week of current date</param>
        /// <returns>Returns the ISO 8601 week number of this instance.</returns>
        public static int WeekIso8601(this DateTime currentDate, out int yearOfWeek)
        {
            int weekNumber = currentDate.WeekIso8601();
            yearOfWeek = currentDate.Year;
            if (currentDate.Month == 1 && weekNumber != _minIso8601WeekNumber)
            {
                yearOfWeek--;
            }
            else if (currentDate.Month == 12 && weekNumber == _minIso8601WeekNumber)
            {
                yearOfWeek++;
            }
            return weekNumber;
        }

        #endregion
    }

}

Open in new window

Output from demo:
1996-12-31 Week: 1997W01 - 1997-01-01 Week: 1997W01
1997-12-31 Week: 1998W01 - 1998-01-01 Week: 1998W01
1998-12-31 Week: 1998W53 - 1999-01-01 Week: 1998W53
1999-12-31 Week: 1999W52 - 2000-01-01 Week: 1999W52
2000-12-31 Week: 2000W52 - 2001-01-01 Week: 2001W01
2001-12-31 Week: 2002W01 - 2002-01-01 Week: 2002W01
2002-12-31 Week: 2003W01 - 2003-01-01 Week: 2003W01
2003-12-31 Week: 2004W01 - 2004-01-01 Week: 2004W01
2004-12-31 Week: 2004W53 - 2005-01-01 Week: 2004W53
2005-12-31 Week: 2005W52 - 2006-01-01 Week: 2005W52
2006-12-31 Week: 2006W52 - 2007-01-01 Week: 2007W01
2007-12-31 Week: 2008W01 - 2008-01-01 Week: 2008W01
2008-12-31 Week: 2009W01 - 2009-01-01 Week: 2009W01
2009-12-31 Week: 2009W53 - 2010-01-01 Week: 2009W53
2010-12-31 Week: 2010W52 - 2011-01-01 Week: 2010W52
2011-12-31 Week: 2011W52 - 2012-01-01 Week: 2011W52
2012-12-31 Week: 2013W01 - 2013-01-01 Week: 2013W01
2013-12-31 Week: 2014W01 - 2014-01-01 Week: 2014W01
2014-12-31 Week: 2015W01 - 2015-01-01 Week: 2015W01
2015-12-31 Week: 2015W53 - 2016-01-01 Week: 2015W53

Open in new window

/gustav
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.