<pre lang="xml">public struct t_IsoWeek
{
static readonly string d_WeekRangeError =
string.Format("Week number must be between {0} and {1}", d_MinWeek, d_MaxWeek);
static readonly string d_YearRangeError =
string.Format("Year number must be between {0} and {1}", d_MinYear, d_MaxYear);
const int d_MinWeek = 1;
const int d_MaxWeek = 53;
const int d_MinYear = 0;
const int d_MaxYear = 9999;
int m_Year;
int m_Week;
public t_IsoWeek(int p_Year, int p_Week)
{
m_Year = d_MinYear;
m_Week = d_MinYear;
Year = p_Year;
Week = p_Week;
}
public t_IsoWeek(DateTime p_Date)
{
m_Year = d_MinYear;
m_Week = d_MinYear;
this = GetIsoWeek(p_Date);
}
public int Week
{
get { return m_Week; }
private set
{
if (value < d_MinWeek || value > d_MaxWeek)
{
throw new ArgumentOutOfRangeException("Week", value, d_WeekRangeError);
}
m_Week = value;
}
}
public int Year
{
get { return m_Year; }
private set
{
if (value < d_MinYear || value > d_MaxYear)
{
throw new ArgumentOutOfRangeException("Year", value, d_YearRangeError);
}
m_Year = value;
}
}
public DateTime EndOfOfWeek
{
get
{
return StartOfWeek.AddDays(6);
}
}
public DateTime StartOfWeek
{
get
{
return GetIsoWeekOne(m_Year).AddDays((m_Week - 1) * 7);
}
}
public bool SpreadsTwoYears
{
get
{
return StartOfWeek.Year != EndOfOfWeek.Year;
}
}
public override string ToString()
{
return string.Format("{0:####}-W{1:##}", m_Year, m_Week);
}
#region Static
public static t_IsoWeek GetIsoWeek(DateTime p_Date)
{
DateTime l_WeekOne;
int l_Year = p_Date.Year;
if (p_Date >= new DateTime(l_Year, 12, 29))
{
l_WeekOne = GetIsoWeekOne(l_Year + 1);
if (p_Date < l_WeekOne)
{
l_WeekOne = GetIsoWeekOne(l_Year);
}
else
{
l_Year++;
}
}
else
{
l_WeekOne = GetIsoWeekOne(l_Year);
if (p_Date < l_WeekOne)
{
l_WeekOne = GetIsoWeekOne(--l_Year);
}
}
int l_Week = (p_Date - l_WeekOne).Days / 7 + 1;
return new t_IsoWeek(l_Year, l_Week);
}
private static DateTime GetIsoWeekOne(int p_Year)
{
DateTime l_Date4Jan = new DateTime(p_Year, 1, 4);
int l_ISODay = GetIsoDayOfWeek(l_Date4Jan);
return l_Date4Jan.AddDays(1 - l_ISODay);
}
public static int GetIsoDayOfWeek(DateTime p_Date)
{
switch (p_Date.DayOfWeek)
{
case DayOfWeek.Monday:
return 1;
case DayOfWeek.Tuesday:
return 2;
case DayOfWeek.Wednesday:
return 3;
case DayOfWeek.Thursday:
return 4;
case DayOfWeek.Friday:
return 5;
case DayOfWeek.Saturday:
return 6;
case DayOfWeek.Sunday:
return 7;
default:
throw new NotImplementedException("DayOfWeek");
}
}
#endregion
}