DateTime 类用于处理日期时间,支持格式化输出、加减计算、获取指定日期(如本月第一天)。
public class DateTimeHelper { // 格式化日期(常用格式) public static string FormatDate(DateTime date, string format = "yyyy-MM-dd HH:mm:ss") { return date.ToString(format); } // 计算两个日期相差天数 public static int GetDaysDifference(DateTime startDate, DateTime endDate) { return Math.Abs((endDate - startDate).Days); } // 获取本月第一天 public static DateTime GetFirstDayOfMonth(DateTime date) { return new DateTime(date.Year, date.Month, 1); } // 日期加N天 public static DateTime AddDays(DateTime date, int days) { return date.AddDays(days); } } // 调用示例 DateTime now = DateTime.Now; Console.WriteLine("当前时间(默认格式):" + DateTimeHelper.FormatDate(now)); Console.WriteLine("当前时间(短日期):" + DateTimeHelper.FormatDate(now, "yyyy-MM-dd")); DateTime start = new DateTime(2024, 1, 1); int days = DateTimeHelper.GetDaysDifference(start, now); Console.WriteLine("距离2024年1月1日相差:" + days + "天"); DateTime firstDay = DateTimeHelper.GetFirstDayOfMonth(now); Console.WriteLine("本月第一天:" + DateTimeHelper.FormatDate(firstDay)); DateTime nextWeek = DateTimeHelper.AddDays(now, 7); Console.WriteLine("一周后:" + DateTimeHelper.FormatDate(nextWeek));