分享

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

 bmal 2011-07-06

八百年一次,这个月有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 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多