首页 > 编程 > C# > 正文

C# 获取当前年份的周期及周期所在日期范围(推荐)

2020-01-24 00:18:10
字体:
来源:转载
供稿:网友

最近有一个项目要用到年份周期,用于数据统计图表展示使用,当中用到年份周期,以及年份周期所在的日期范围。当初设想通过已知数据来换算年份周期,经过搜索资料发现通过数据库SQL语句来做,反而更加复杂。现在改变思路通过C#后台代码来算出两段日期范围中年份周期,在依据年份周期所对应的日期范围进行数据库查询进行统计。需要解决以下两个点问题,

第一点:依据日期查找所在年份的第几周;

第二点:依据年份所在的周期计算出周期所在的日期范围。

using System;using System.Collections.Generic;using System.Globalization;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication6{  class Program  {    static void Main(string[] args)    {      GregorianCalendar gc = new GregorianCalendar();      int weekOfYear = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);      Console.WriteLine("当前第{0}周", weekOfYear);      DateTime startDate, lastDate;      for (int i = 1; i <= 53; i++)      {        GetDaysOfWeeks(DateTime.Now.Year, i, out startDate, out lastDate);        Console.WriteLine("第{0}周", i);        Console.WriteLine(startDate);        Console.WriteLine(lastDate);      }      Console.ReadLine();    }    public static bool GetDaysOfWeeks(int year, int index, out DateTime first, out DateTime last)    {      first = DateTime.MinValue;      last = DateTime.MinValue;      if (year < 1700 || year > 9999)      {        //"年份超限"        return false;      }      if (index < 1 || index > 53)      {        //"周数错误"        return false;      }      DateTime startDay = new DateTime(year, 1, 1); //该年第一天      DateTime endDay = new DateTime(year + 1, 1, 1).AddMilliseconds(-1);      int dayOfWeek = 0;      if (Convert.ToInt32(startDay.DayOfWeek.ToString("d")) > 0)        dayOfWeek = Convert.ToInt32(startDay.DayOfWeek.ToString("d")); //该年第一天为星期几      if (dayOfWeek == 0) { dayOfWeek = 7; }      if (index == 1)      {        first = startDay.AddDays(7 - dayOfWeek - 6);        if (dayOfWeek == 6)        {          last = first;        }        else        {          last = startDay.AddDays((7 - dayOfWeek));        }      }      else      {        first = startDay.AddDays((8 - dayOfWeek) + (index - 2) * 7); //index周的起始日期        last = first.AddDays(6);        //if (last > endDay)        //{        //  last = endDay;        //}      }      if (first > endDay) //startDayOfWeeks不在该年范围内      {        //"输入周数大于本年最大周数";        return false;      }      return true;    }  }}

  执行结果 

总结

以上所述是小编给大家介绍的C# 获取当前年份的周期及周期所在日期范围(推荐),希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表