C#获取指定月指定周的日期范围 根据当前时间获取本月开始日期和结束日期

46 篇文章 0 订阅
[csharp]  view plain copy print ?
  1. /// <summary>  
  2. /// 获取指定月份指定周数的开始日期  
  3. /// </summary>  
  4. /// <param name="year">年份</param>  
  5. /// <param name="month">月份</param>  
  6. /// <param name="index">周数</param>  
  7. /// <returns></returns>  
  8. private DateTime GetStartDayOfWeeks(int year, int month, int index)  
  9. {  
  10.     if (year < 1600 || year > 9999)  
  11.     {  
  12.         MessageBox.Show("年份超限");  
  13.         return DateTime .MinValue ;  
  14.     }  
  15.     if (month < 0 || month > 12)  
  16.     {  
  17.         MessageBox.Show("月份错误");  
  18.         return DateTime .MinValue ;  
  19.     }  
  20.     if (index < 1)  
  21.     {  
  22.         MessageBox.Show("周数错误");  
  23.         return DateTime.MinValue;  
  24.     }  
  25.     DateTime startMonth = new DateTime(year, month, 1);  //该月第一天  
  26.     int dayOfWeek = 7;  
  27.     if (Convert.ToInt32(startMonth.DayOfWeek.ToString("d")) > 0)  
  28.         dayOfWeek = Convert.ToInt32(startMonth.DayOfWeek.ToString("d"));  //该月第一天为星期几  
  29.     DateTime startWeek = startMonth.AddDays(1 - dayOfWeek);  //该月第一周开始日期  
  30.     //DateTime startDayOfWeeks = startWeek.AddDays((index - 1) * 7);  //index周的起始日期  
  31.     DateTime startDayOfWeeks = startWeek.AddDays(index * 7);  //index周的起始日期  
  32.     if ((startDayOfWeeks - startMonth.AddMonths(1)).Days > 0)  //startDayOfWeeks不在该月范围内  
  33.     {  
  34.         MessageBox.Show("输入周数大于本月最大周数");  
  35.         return DateTime.MinValue;  
  36.     }  
  37.     return startDayOfWeeks;  
  38. }  


 

[csharp]  view plain copy print ?
  1. //当前时间  
  2. DateTime dt = DateTime.Now;  
  3. //本月第一天时间      
  4. DateTime dt_First = dt.AddDays(1 - (dt.Day));  
  5. //获得某年某月的天数    
  6. int year = dt.Date.Year;  
  7. int month = dt.Date.Month;  
  8. int dayCount = DateTime.DaysInMonth(year, month);  
  9. //本月最后一天时间    
  10. DateTime dt_Last = dt_First.AddDays(dayCount - 1);  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值