EasyText, EasyLicense 的作者, https://github.com/EasyHelper Good Good Study,Day Day Up.

 

八百年一次,这个月有5个礼拜五,5个礼拜六,5个礼拜天

昨天在微博上看到有人说:

image

 

看看日历,的确是这样:

image

 

但是凭程序员的直觉,感觉下一次,应该不需要800年啊,于是做了如下测试:

 

判断有5个礼拜五,5个礼拜六,5个礼拜天的方法:

1:该月必须有31天

2:该月1号必须是星期5.

 

static void Main(string[] args)
{
    DateTime dtNow = DateTime.Now;

    while (dtNow < DateTime.MaxValue)
    {
        DateTime nextMonth = dtNow.AddMonths(1);
        DateTime firstDayOfNextMonth=new DateTime(nextMonth.Year,nextMonth.Month,1);
        if (DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month) == 31 &&
            firstDayOfNextMonth.DayOfWeek == DayOfWeek.Friday)
        {
            Console.WriteLine("下一次是:{0}",firstDayOfNextMonth);
            break;
        }

        dtNow = nextMonth;
    }

    Console.ReadLine();
}
代码比较简单,无非就是一个月一个月的检查,并判断是否符合上面的两点。
运行结果如下:
image 
image 
 
 
那看下上次发生是什么时候吧,把DateTime nextMonth = dtNow.AddMonths(1); 
变成DateTime nextMonth = dtNow.AddMonths(-1);
接着把dtNow<DateTime.MaxValue 该为 DateTime.MinValue<=dtNow
 
就可以了,运行结果如下:
image 
image 
 
posted @ 2011-07-06 05:59  LoveJenny  阅读(28198)  评论(84编辑  收藏  举报
EasyText, EasyLicense 的作者, https://github.com/EasyHelper Good Good Study,Day Day Up.