C产品如何满足特定用户需求?
- 内容介绍
- 文章标签
- 相关推荐
本文共计707个文字,预计阅读时间需要3分钟。
直接使用`DateTime.DaysInMonth()`函数配合年月可以更稳定地计算一个月的天数,无需依赖当前日期的减一天技巧。例如,计算2024年3月的天数可以使用以下代码:
核心逻辑:先拿到上个月的年份和月份,再用 DateTime.DaysInMonth(year, month) 得到最后一天的日期数,拼成完整 DateTime:
int year = DateTime.Now.Year; int month = DateTime.Now.Month; if (month == 1) { year--; month = 12; } else { month--; } int lastDay = DateTime.DaysInMonth(year, month); DateTime lastDateOfLastMonth = new DateTime(year, month, lastDay);
这段代码能正确处理 1 月 → 上一年 12 月、闰年 2 月(29 天)等边界情况。
本文共计707个文字,预计阅读时间需要3分钟。
直接使用`DateTime.DaysInMonth()`函数配合年月可以更稳定地计算一个月的天数,无需依赖当前日期的减一天技巧。例如,计算2024年3月的天数可以使用以下代码:
核心逻辑:先拿到上个月的年份和月份,再用 DateTime.DaysInMonth(year, month) 得到最后一天的日期数,拼成完整 DateTime:
int year = DateTime.Now.Year; int month = DateTime.Now.Month; if (month == 1) { year--; month = 12; } else { month--; } int lastDay = DateTime.DaysInMonth(year, month); DateTime lastDateOfLastMonth = new DateTime(year, month, lastDay);
这段代码能正确处理 1 月 → 上一年 12 月、闰年 2 月(29 天)等边界情况。

