如何使用c#.net查找每月的第二和第四个星期六
问题描述:
使用C#.net识别每个月的第二个和第四个星期六
我尝试过:
使用C#.net
Identify Second and Fourth Saturdays of Each Month using C#.net
What I have tried:
Identify Second and Fourth Saturdays of Each Month using C#.net
答
识别每个月的第二个和第四个星期六我有点忙,但我写了Linq方法从列表获得2.和4.星期六< DateTime>
:
I'm bit busy, but i wrote Linq method to get 2. and 4. saturday from theList<DateTime>
:
List<DateTime> MyCalendar = new List<DateTime>(); //create list
DateTime currDate = new DateTime(2016,1,1); //initial value
//add days to MyCalendar
while(currDate<=new DateTime(2016,12,31))
{
MyCalendar.Add(currDate);
currDate = currDate.AddDays(1);
}
//method to get 2. and 4. saturday in month
var result = MyCalendar.Where(x=>x.DayOfWeek==DayOfWeek.Saturday)
.GroupBy(x=>x.Month)
.SelectMany(grp=>
grp.Select((d, counter)=>new
{
Month = grp.Key,
PosInMonth = counter+1,
Day = d
}))
.Where(x=>x.PosInMonth==2 || x.PosInMonth==4)
.ToList();
为了能够查看结果列表,你必须使用 foreach(。 ..){}
循环。
To be able to go through the result list, you have to use foreach(...){}
loop.
foreach(var d in result)
{
Console.WriteLine("{0} {1} {2}", d.Month, d.PosInMonth, d.Day);
}
重要说明:我建议编写继承自日历 [ ^ ]要扩展它在 GetNthDayInMonth()
上的方法。这应该使您有可能使自定义日历以特定的文化 [ ^ ]。
试试!
Important note: I'd suggest to write custom class which inherits from Calendar[^] to extend its methods on GetNthDayInMonth()
. This should give you a possibilty to make custom calendar conditional on specific Culture[^].
Try!
这是一个简单的解决方案。
Here is simple solution.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Second Saturday of Month: " + GetSaturdayByWeek(DateTime.Now, 2).ToShortDateString());
Console.WriteLine("Fourth Saturdays of Month: " + GetSaturdayByWeek(DateTime.Now, 4).ToShortDateString());
}
private static DateTime GetSaturdayByWeek(DateTime dateofMonth, int weekNumber)
{
DateTime firstDateofMonth = new DateTime(dateofMonth.Year, dateofMonth.Month, 1);
DateTime resultDate = CultureInfo.InvariantCulture.Calendar.AddWeeks(firstDateofMonth, weekNumber - 1);
int day = Convert.ToInt32(resultDate.DayOfWeek) < 6 ? (Convert.ToInt32(resultDate.DayOfWeek) - 6) * -1 : 0;
return resultDate.AddDays(day);
}
}
查看开发人员的小巷|如何获得一个月的第n天 [ ^ ]