这篇文章主要介绍了C# 获取当前年份的周期,周期所在日期范围 ,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
最近有一个项目要用到年份周期,用于数据统计图表展示使用,当中用到年份周期,以及年份周期所在的日期范围。当初设想通过已知数据来换算年份周期,经过搜索资料发现通过数据库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;
/
沃梦达教程
本文标题为:C# 获取当前年份的周期及周期所在日期范围(推荐)
基础教程推荐
猜你喜欢
- winform把Office转成PDF文件 2023-06-14
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- C#控制台实现飞行棋小游戏 2023-04-22
- ZooKeeper的安装及部署教程 2023-01-22
- C# List实现行转列的通用方案 2022-11-02
- C# windows语音识别与朗读实例 2023-04-27
- 一个读写csv文件的C#类 2022-11-06
- unity实现动态排行榜 2023-04-27
- C# 调用WebService的方法 2023-03-09
- C#类和结构详解 2023-05-30