1.取某月的最后一天
1 //1.使用算出该月多少天,年+月+加上多少天即可,举例取今天最后一天 2 private static void GetLastDateForMonth(DateTime dtStart,out DateTime dtEnd) 3 { 4 int dtYear, dtMonth; 5 //dtStart = DateTime.Now; 6 dtYear = dtStart.Year; 7 dtMonth = dtStart.Month; 8 int MonthCount = DateTime.DaysInMonth(dtYear, dtMonth); 9 dtEnd = Convert.ToDateTime(dtYear.ToString() + "-" + dtMonth.ToString() + "-" + MonthCount); 10 11 }
1 private static void GetLastDateForMonth(DateTime dtStart, out DateTime dtEnd) 2 { 3 int dtYear, dtMonth; 4 DateTime dtStart2= dtStart.AddMonths(1); 5 dtYear = dtStart2.Year; 6 dtMonth = dtStart2.Month; 7 dtEnd = Convert.ToDateTime(dtYear.ToString() + "-" + dtMonth.ToString() + "-" + "1").AddDays(-1); 8 9 }
2.时间差的计算TimeSpan
1 DateTime dt1 = new DateTime(2021, 5, 18, 14, 23,22); 2 DateTime dt2 = DateTime.Now; 3 TimeSpan ts = dt1.Subtract(dt2); 4 Console.WriteLine($"相差{ts.Days}天{ts.Hours}小时{ts.Minutes}分钟{ts.Seconds}秒"); 5 Console.ReadKey();