Ne avevo già parlato anni fa, e il problema si ripresenta spesso per cui mi sono detto, perché non creare degli Extension Methods che mi facciano tutto il lavoro sporco?
Sperando di fare cosa gradita ve l’allego 
public static class ExtensionMethods
{
public static int WeekNumber(this DateTime date)
{
var year = date.Year;
DateTime week1;
if (date >= new DateTime(year, 12, 29))
{
week1 = GetWeekOneDate(year + 1);
if (date < week1)
{
week1 = GetWeekOneDate(year);
}
}
else
{
week1 = GetWeekOneDate(year);
if (date < week1)
{
week1 = GetWeekOneDate(System.Threading.Interlocked.Decrement(ref year));
}
}
return Convert.ToInt32(Math.Truncate((decimal) (date - week1).Days/7 + 1));
}
private static DateTime GetWeekOneDate(int year)
{
// Get the date for Jan-4 for the given year
var date = new DateTime(year, 1, 4);
// Get the ISO-8601 day number for this date 1==Monday, 7==Sunday
var dayNum = (int) date.DayOfWeek;
// 0==Sunday, 6==Saturday
if (dayNum == 0)
dayNum = 7;
// Return the date of the Monday that is less than or equal to this date
return date.AddDays(1 - dayNum);
}
public static DateTime WeekStartingDay(this DateTime date)
{
var dayNum = (int)date.DayOfWeek;
if (dayNum == 0)
dayNum = 7;
return date.AddDays(1 - dayNum).Date;
}
public static string WeekString(this DateTime date)
{
return date.Year.ToString() + "/" + WeekOfYear(date).ToString("00");
}
}
Piccoli programmatori crescono 
posted @ martedì 12 marzo 2013 16:57