星期三, 4月 01, 2009

(題目)如何去抓出雙數周的週六

今天看到一個題目"如何去抓出雙數周,用來判斷隔週休"..隨手寫了程式..紀錄一下..Tongue out..

這樣執行就可以列出第雙數週週六了

WeekSpProvider wp = new WeekSpProvider(2009, 4, DayOfWeek.Saturday, 12);
var data = wp.GetDateTimeList(2);
foreach (var a in data)
Response.Write(a.Date.ToString("yyyy/MM/dd")+"<br />");

class:

/// <summary>
/// 來處理數個月的資料
/// </summary>
public class WeekSpProvider
{
List<DateObj> dateTimeList = new List<DateObj>();
public WeekSpProvider(int startYear, int startMonth, DayOfWeek dayWeek, int monthCount)
{
DateTime dtStart = new DateTime(startYear, startMonth, 1);
for (int i = 1; i <= monthCount; i++)
{
MonthObj mo = new MonthObj(dtStart, dayWeek);
this.dateTimeList = this.dateTimeList
.Union(mo.GetDateTimeList()).ToList();
dtStart = dtStart.AddMonths(1);
}
}
/// <summary>
/// 找到倍數的週數
/// </summary>
/// <param name="multiplier"></param>
/// <returns></returns>
public List<DateObj> GetDateTimeList(int multiplier)
{
return this.dateTimeList.Where(a => a.Number % multiplier == 0).ToList();
}
}
/// <summary>
/// 處理一個月的月份
/// </summary>
public class MonthObj
{
int year;
int month;
List<DateObj> dateTimeList = new List<DateObj>();
DateTime nextMonth;
DayOfWeek dayWeek;
public MonthObj(DateTime dt, DayOfWeek dayWeek)
{
this.year = dt.Year;
this.month = dt.Month;
this.dayWeek = dayWeek;
//抓出這個月第一天,跟下個月的第一天
DateTime dateTime = new DateTime(year, month, 1);
nextMonth = dateTime.AddMonths(1);
//迴圈去取得每一周
int i = 0;
do
{
if (IsYouWantDay(dateTime))
{
AddDate(++i, dateTime);
dateTime = dateTime.AddDays(7);
}
else
{
dateTime = dateTime.AddDays(1);
}
}
while (dateTime < nextMonth);
}
public List<DateObj> GetDateTimeList()
{
return dateTimeList;
}
private void AddDate(int number, DateTime dt)
{
if (dt < nextMonth)
this.dateTimeList.Add(
new DateObj() { Number = number, Month = dt.Month, Date = dt, DayWeek = dayWeek });
}
private bool IsYouWantDay(DateTime dt)
{
return dt.DayOfWeek == dayWeek;
}
}
/// <summary>
/// 來紀錄日期的資料
/// </summary>
public struct DateObj
{
public int Number { get; set; }
public int Month { get; set; }
public DayOfWeek DayWeek { get; set; }
public DateTime Date { get; set; }
}

這class還可以作到類似下列的效果..

ghj

試試看ㄅ..蠻不錯玩的..Nerd..

沒有留言: