基础方法:使用DateTime结构
运行结果中,若当前日期为1月31日,
AddDays(1)
会自动转为2月1日,体现方法的智能性。
便捷扩展:DateTimeExtensions扩展方法
为提升代码复用性,可自定义
DateTimeExtensions
类封装常用日期加减操作。
public static class DateExtensions{public static DateTime AddDays(This DateTime date, int days){return date.AddDays(days);}public static DateTime AddMonths(this DateTime date, int months){return date.AddMonths(months);}public static DateTime AddYears(this DateTime date, int years){return date.AddYears(years);}}
使用时直接调用:
var result = DateTime.Now.AddDays(5).AddMonths(-2);
该方法使代码更简洁,避免重复书写实例方法。
LINQ辅助:使用DateTimeExtensions(LINQ)
在处理日期集合时,LINQ的
DateTimeExtensions
也能提供便利,获取当前日期后3个月的日期范围:
var startDate = DateTime.Now;var endDate = startDate.AddMonths(3);var dateRange = Enumerable.Range(0, 31).Select(i => startDate.AddDays(i)).ToList();
public static class CustomDateHelper{public static int WorkDaysBetween(DateTime start, DateTime end){int workDays = 0;DateTime current = start;while (current <= end){if (current.DayOfWeek != DayOfWeek.Saturday && current.DayOfWeek != DayOfWeek.Sunday){workDays++;}current = current.AddDays(1);}return workDays;}}
调用方式:
var workDays = CustomDateHelper.WorkDaysBetween(DateTime.Now, DateTime.Now.AddDays(14));



![一文解析实现方法-jQuery如何获取当前域名 (实现怎么解释,no_ai_sug:false}],slid:178026119233981,queryid:0x1d8a1e9ef9901bd)](https://www.kuidc.com/zdmsl_image/article/20260211204532_42753.jpg)










发表评论