最近有个统计分布的需求,需要按统计本周,上周,本月,上月,本季度,上季度,本年度,上年度等时间统计分布趋势,所以这里就涉及到计算周,月,季度,年度等的起止时间了,下面总结一下C#中关于根据当前时间获取周,月,季度,年度等时间段的起止时间的方法,废话不多说,直接贴代码,如果你觉得有用,请多多推荐。
DateTime dt = DateTime.Now; //当前时间 DateTime startWeek = dt.AddDays( - Convert.ToInt32(dt.DayOfWeek.ToString("d"))); //本周周一 DateTime endWeek = startWeek.AddDays(); //本周周日 DateTime startMonth = dt.AddDays( - dt.Day); //本月月初 DateTime endMonth = startMonth.AddMonths().AddDays(-); //本月月末// endMonth = startMonth.AddDays((dt.AddMonths() - dt).Days - ); //本月月末 DateTime startQuarter = dt.AddMonths( - (dt.Month - ) % ).AddDays( - dt.Day); //本季度初 DateTime endQuarter = startQuarter.AddMonths().AddDays(-); //本季度末 DateTime startYear = , ); //本年年初 DateTime endYear = , ); //本年年末至于昨天、明天、上周、上月、上季度、上年度等等, - Convert.ToInt32(DateTime.Now.DayOfWeek)) - ); //上周一 - Convert.ToInt32(DateTime.Now.DayOfWeek)) - ).AddDays(); //上周末(星期日)//下周 - Convert.ToInt32(DateTime.Now.DayOfWeek)) + ); //下周一 - Convert.ToInt32(DateTime.Now.DayOfWeek)) + ).AddDays(); //下周末 DateTime.Parse(DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + ).AddDays(-).ToShortDateString();//最后一天 //巧用C#里ToString的字符格式化更简便 DateTime.Now.ToString("yyyy-MM-01");//本月初 DateTime.Parse(DateTime.Now.ToString().AddDays(-).ToShortDateString();//本月最后一天 DateTime.Parse(DateTime.Now.ToString().ToShortDateString();//上个月1号 DateTime.Parse(DateTime.Now.ToString().ToShortDateString();//上个月最后一天 DateTime.Parse(DateTime.Now.ToString().ToShortDateString();// 下个月1号 DateTime.Parse(DateTime.Now.ToString().AddDays(-).ToShortDateString();//下下月最后一天 DateTime.Now.AddDays().ToShortDateString();//7天后 DateTime.Now.AddDays(-).ToShortDateString();//7天前 DateTime.Now.Date.ToShortDateString();//本年度,用ToString的字符格式化我们也很容易地算出本年度的第一天和最后一天 DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).ToShortDateString();//本年度第一天 DateTime.Parse(DateTime.Now.ToString().AddDays(-).ToShortDateString();//本年度最后一天 DateTime.Parse(DateTime.Now.ToString().ToShortDateString(); //上年度第一天, DateTime.Parse(DateTime.Now.ToString().ToShortDateString();//上年度第最后一天, DateTime.Parse(DateTime.Now.ToString().ToShortDateString(); //下年度第一天 DateTime.Parse(DateTime.Now.ToString().AddDays(-).ToShortDateString();//下年度最后一天 //本季度, DateTime.Now.AddMonths( - ((DateTime.Now.Month - ) % )).AddDays( - DateTime.Now.Day);//本季度第一天; DateTime.Parse(DateTime.Now.AddMonths( - ((DateTime.Now.Month - ) % )).ToString().ToShortDateString();//本季度的最后一天 DateTime.Now.AddMonths( - ((DateTime.Now.Month - ) % )).ToString("yyyy-MM-01");//下季度的第一天 DateTime.Parse(DateTime.Now.AddMonths( - ((DateTime.Now.Month - ) % )).ToString().ToShortDateString();// 下季度最后一天 DateTime.Now.AddMonths(- - ((DateTime.Now.Month - ) % )).AddDays( - DateTime.Now.Day);// 上季度第一天 DateTime.Now.AddMonths( - ((DateTime.Now.Month - ) % )).AddDays( - DateTime.Now.Day).AddDays(-).ToShortDateString();// 上季度最后一天
另外,提前透露一下,后续几天会陆续推出web在线打印,在线设计,打印阅览博客一篇,word,PPT,Excel,PDF在线阅览一篇,请大家多多支持。