如何使用c#.net查找每月的第二和第四个星期六 [英] How to find second and fourth saturdays of each month using c#.net

查看:55
本文介绍了如何使用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 the List<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);
}





重要说明:我建议编写继承自<的自定义类a href =https://msdn.microsoft.com/en-us/library/system.globalization.calendar%28v=vs.110%29.aspx>日历 [ ^ ]要扩展它在 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天 [ ^ ]


这篇关于如何使用c#.net查找每月的第二和第四个星期六的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆