首页 > Windows开发 > 详细

c#经典题目-- 年、周、日期计算

时间:2017-08-20 23:10:42      阅读:324      评论:0      收藏:0      [点我收藏+]
/// /// 获取一年中指定的一周的开始日期和结束日期。开始日期为星期一。 /// /// /// 年(1 到 9999) /// 周(1 到 53) /// 确定首周的规则 /// 当此方法返回时,则包含参数 year 和 weeks 指定的周的开始日期的 System.DateTime 值;如果失败,则为 System.DateTime.MinValue。如果参数 year 或 weeks 超出有效范围,则操作失败。该参数未经初始化即被传递。 /// 当此方法返回时,则包含参数 year 和 weeks 指定的周的结束日期的 System.DateTime 值;如果失败,则为 System.DateTime.MinValue。如果参数 year 或 weeks 超出有效范围,则操作失败。该参数未经初始化即被传递。 /// public static bool GetDaysOfWeeks(int year, int weeks, CalendarWeekRule weekrule, out DateTime first, out DateTime last) { //初始化 out 参数 first = DateTime.MinValue; last = DateTime.MinValue; //不用解释了吧... if (year < 1 | year > 9999) return false; //一年最多53周地球人都知道... if (weeks < 1 | weeks > 53) return false; //取当年首日为基准...为什么?容易得呗... DateTime firstCurr = new DateTime(year, 1, 1); //取下一年首日用于计算... DateTime firstNext = new DateTime(year + 1, 1, 1); //将当年首日星期几转换为数字...星期日特别处理...ISO 8601 标准... int dayOfWeekFirst = (int)firstCurr.DayOfWeek; if (dayOfWeekFirst == 0) dayOfWeekFirst = 7; //得到未经验证的周首日... first = firstCurr.AddDays((weeks - 1) * 7 - dayOfWeekFirst + 1); //周首日是上一年日期的情况... if (first.Year < year) { switch (weekrule) { case CalendarWeekRule.FirstDay: //不用解释了吧... first = firstCurr; break; case CalendarWeekRule.FirstFullWeek: //顺延一周... first = first.AddDays(7); break; case CalendarWeekRule.FirstFourDayWeek: //周首日距年首日不足4天则顺延一周... if (firstCurr.Subtract(first).Days > 3) { first = first.AddDays(7); } break; default: break; } } //得到未经验证的周末日... last = first.AddDays(7).AddSeconds(-1); switch (weekrule) { case CalendarWeekRule.FirstDay: //周末日是下一年日期的情况... if (last.Year > year) last = firstNext.AddSeconds(-1); else if (last.DayOfWeek != DayOfWeek.Monday) last = first.AddDays(7 - (int)first.DayOfWeek).AddSeconds(-1); break; case CalendarWeekRule.FirstFourDayWeek: //周末日距下一年首日不足4天则提前一周... if (last.Year > year && firstNext.Subtract(first).Days < 4) { first = first.AddDays(-7); last = last.AddDays(-7); } break; default: break; } return true; } /// /// 获取指定日期在某年的周数 /// /// /// private int GetWeekOfYear(DateTime dt) { GregorianCalendar gc = new GregorianCalendar(); return gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday); }

c#经典题目-- 年、周、日期计算

原文:http://www.cnblogs.com/Sharpay/p/7401697.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!