如何从自定义DateTime变量LastUpdatedAt获取前1个月的日期时间?
解决DateTime变量往前推1个月的问题
嘿,这个问题其实很好解决——你可能搞混了方法的调用对象啦!
AddMonths是DateTime实例的方法,它不是只能依附在DateTime.Now上使用。你的LastUpdatedAt本身就是一个标准的DateTime类型变量,直接在它上面调用AddMonths方法,传入负数参数就表示往前推指定月份数。
具体实现步骤
- 假设你已经正确获取到了
LastUpdatedAt变量:
var LastUpdatedAt = ctx.SearchedUsers.Where(x => x.SearchId == searchId) .Select(x => x.LastUpdatedAt) .FirstOrDefault();
- 直接调用
AddMonths(-1)得到往前推1个月的时间:
var oneMonthPrior = LastUpdatedAt.AddMonths(-1);
额外注意事项
- 要留意
LastUpdatedAt可能的默认值:如果你的查询没有找到匹配数据,LastUpdatedAt会是DateTime.MinValue,建议先做有效性判断再处理:
if (LastUpdatedAt != DateTime.MinValue) { var oneMonthPrior = LastUpdatedAt.AddMonths(-1); // 在这里编写你的业务逻辑 }
AddMonths方法会自动处理月末的边界情况:比如如果LastUpdatedAt是2024年3月31日,往前推1个月会自动调整为2024年2月29日(闰年),无需手动计算。
内容的提问来源于stack exchange,提问作者John Haga
相关产品推荐
相关产品推荐

