C# 时间处理
using System; using System.Globalization; namespace Common { /// <summary> /// 时间处理 /// </summary> public class DateTimeCommonHandler { /// <summary> /// 获取时间是一年的第几周 /// </summary> /// <param name="dt"></param> /// <returns></returns> public int GetWeekNum(DateTime dt) { GregorianCalendar gc = new GregorianCalendar(); int weekOfYear = gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday); return weekOfYear; } /// <summary> /// C#获取指定日期时间是当前年度的第几个季度 /// </summary> /// <param name="dt"></param> /// <returns></returns> public int GetQuarterNum(DateTime dt) { var mouth = dt.Month; int quarter = mouth % 3 == 0 ? mouth / 3 : (mouth / 3 + 1); return quarter; } /// <summary> /// 求时间段间隔天数 /// </summary> /// <param name="dateStart"></param> /// <param name="dateEnd"></param> /// <returns></returns> public int DateDiff(DateTime dateStart, DateTime dateEnd) { DateTime start = Convert.ToDateTime(dateStart.ToShortDateString()); DateTime end = Convert.ToDateTime(dateEnd.ToShortDateString()); TimeSpan sp = end.Subtract(start); return sp.Days + 1; } } }
获取时间段内的时间:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Common { public static class ComputeDateDiff { public static List<DateTimeDto> GetDateAll(DateTime beginDate, DateTime endDate) { List<DateTimeDto> list = new List<DateTimeDto>(); //不跨年的 if (beginDate.Year == endDate.Year) { //不跨月的 if (endDate.Month == beginDate.Month) { list.Add(new DateTimeDto() { BeginDate = beginDate, EndDate = endDate }); } //跨月的 else { GetMouth(beginDate, endDate, ref list); } } //跨年的 else { for (int i = beginDate.Year; i <= endDate.Year; i++) { DateTime startDateTime = new DateTime(i, 1, 1); DateTime endDateTime = new DateTime(i, 12, 31); if (i == beginDate.Year) { startDateTime = beginDate; } else if (i == endDate.Year) { endDateTime = endDate; } GetMouth(startDateTime, endDateTime, ref list); } } return list; } public static void GetMouth(DateTime beginDate, DateTime endDate, ref List<DateTimeDto> list) { for (int i = beginDate.Month; i <= endDate.Month; i++) { if (i == beginDate.Month) { list.Add(new DateTimeDto() { BeginDate = beginDate, EndDate = new DateTime(beginDate.Year, beginDate.Month + 1, 1).AddDays(-1) }); } else if (i == endDate.Month) { list.Add(new DateTimeDto() { BeginDate = new DateTime(beginDate.Year, i, 1), EndDate = endDate }); } else { list.Add(new DateTimeDto() { BeginDate = new DateTime(beginDate.Year, i, 1), EndDate = new DateTime(beginDate.Year, i + 1, 1).AddDays(-1) }); } } } } public class DateTimeDto { public DateTime BeginDate { get; set; } public DateTime EndDate { get; set; } } }
莫谈他人高薪,且看闲时谁在拼.