C#中关于常用日期的计算
void Main() { DateTime dt = DateTime.Now; //当前时间 DateTime startWeek = dt.AddDays(1 - Convert.ToInt32(dt.DayOfWeek.ToString("d"))); //本周周一 DateTime endWeek = startWeek.AddDays(6);//本周周日 DateTime startMonth = dt.AddDays(1-dt.Day);//本月月初 DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);//本月月末 DateTime startQuarter = dt.AddMonths(0 - (dt.Month - 1) % 3).AddDays(1 - dt.Day); //本季度初 DateTime endQuarter = startQuarter.AddMonths(3).AddDays(-1); //本季度末 DateTime startYear = new DateTime(dt.Year, 1, 1); //本年年初 DateTime endYear = new DateTime(dt.Year, 12, 31); //本年年末 var startQuarter2 = startYear.AddMonths(3);//2季度初 var endQuarter1 = startQuarter2.AddDays(-1);//1季度末 var startQuarter3 = startYear.AddMonths(6);//3季度初 var endQuarter2 = startQuarter3.AddDays(-1);//2季度末 var startQuarter4 = startYear.AddMonths(9);//4季度初 var endQuarter3 = startQuarter4.AddDays(-1);//3季度末 Console.WriteLine("本周周一:" + startWeek.ToString("yyyy-MM-dd")); Console.WriteLine("本周周末:" + endWeek); Console.WriteLine("\r\n本月月初:" + startMonth); Console.WriteLine("本月月末:" + endMonth); Console.WriteLine("\r\n本季度初:" + startQuarter); Console.WriteLine("本季度末:" + endQuarter); Console.WriteLine("\r\n本年年初:" + startYear); Console.WriteLine("本年年末:" + endYear); Console.WriteLine("\r\n一季度初:" + startYear); Console.WriteLine("一季度末:" + endQuarter1); Console.WriteLine("\r\n二季度初:" + startQuarter); Console.WriteLine("二季度末:" + endQuarter2); Console.WriteLine("\r\n三季度初:" + startQuarter); Console.WriteLine("三季度末:" + endQuarter3); Console.WriteLine("\r\n四季度初:" + startQuarter); Console.WriteLine("四季度末:" + endYear); Console.WriteLine(); System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime( new System.DateTime(1970, 1, 1)); // 当地时区 long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数 Console.WriteLine("时间戳:" + timeStamp); }
结果:
本周周一:2019-08-12 本周周末:2019-08-18 17:44:42 本月月初:2019-08-01 17:44:42 本月月末:2019-08-31 17:44:42 本季度初:2019-07-01 17:44:42 本季度末:2019-09-30 17:44:42 本年年初:2019-01-01 00:00:00 本年年末:2019-12-31 00:00:00 一季度初:2019-01-01 00:00:00 一季度末:2019-03-31 00:00:00 二季度初:2019-07-01 17:44:42 二季度末:2019-06-30 00:00:00 三季度初:2019-07-01 17:44:42 三季度末:2019-09-30 00:00:00 四季度初:2019-07-01 17:44:42 四季度末:2019-12-31 00:00:00 时间戳:1565862282444