如何根据1-12范围内的月份数字获取对应月份的起止日期?
根据月份数字获取对应月份的起止日期
嘿,这个需求太常见了!不管是做报表统计还是数据筛选,经常需要根据月份数字拿到对应的起止日期。我来给你分享几种主流编程语言的实现方法,都是经过验证的靠谱方案:
Python 实现
Python的datetime模块就能轻松搞定,核心思路是先确定当月第一天,再通过下个月第一天减一天得到当月最后一天,自动处理闰年2月的情况:
import datetime def get_month_range(year, month): # 当月起始日期固定为1号 start_date = datetime.date(year, month, 1) # 计算下个月的1号,用来推导当月最后一天 if month == 12: next_month = datetime.date(year + 1, 1, 1) else: next_month = datetime.date(year, month + 1, 1) end_date = next_month - datetime.timedelta(days=1) # 格式化为YYYY-MM-DD的字符串返回 return f"{start_date.strftime('%Y-%m-%d')} - {end_date.strftime('%Y-%m-%d')}" # 测试:获取2018年1月的日期区间 print(get_month_range(2018, 1)) # 输出:2018-01-01 - 2018-01-31
JavaScript 实现
JS的Date对象有个小技巧:传入月份参数为当月数值、日期为0时,会自动返回当月最后一天。注意JS的月份是从0开始计数的,所以要做个小转换:
function getMonthRange(year, month) { // JS月份从0开始,所以要减1得到正确的当月起始日期 const startDate = new Date(year, month - 1, 1); // 传入month作为月份参数、日期为0,直接得到当月最后一天 const endDate = new Date(year, month, 0); // 封装日期格式化函数,确保输出YYYY-MM-DD格式 const formatDate = (date) => { const y = date.getFullYear(); const m = String(date.getMonth() + 1).padStart(2, '0'); const d = String(date.getDate()).padStart(2, '0'); return `${y}-${m}-${d}`; }; return `${formatDate(startDate)} - ${formatDate(endDate)}`; } // 测试:获取2020年2月(闰年)的日期区间 console.log(getMonthRange(2020, 2)); // 输出:2020-02-01 - 2020-02-29
Java 实现
如果用Java 8及以上版本,推荐用LocalDate类,API简洁又好用,同样通过“下个月第一天减一天”的思路实现:
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class MonthRangeUtil { public static String getMonthRange(int year, int month) { // 构造当月第一天的日期对象 LocalDate startDate = LocalDate.of(year, month, 1); // 下个月第一天减一天,就是当月最后一天 LocalDate endDate = startDate.plusMonths(1).minusDays(1); // 定义日期格式化器 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); return startDate.format(formatter) + " - " + endDate.format(formatter); } public static void main(String[] args) { // 测试:获取2018年12月的日期区间 System.out.println(getMonthRange(2018, 12)); // 输出:2018-12-01 - 2018-12-31 } }
通用核心思路
不管用哪种语言,最稳妥的方式都是:
- 当月起始日期固定为当月1号;
- 通过计算下个月的第一天,再减去一天得到当月最后一天。
这种方法不需要手动维护每个月的天数表,还能自动处理闰年的2月,避免了手动判断的繁琐和出错概率。
内容的提问来源于stack exchange,提问作者Karabah
相关产品推荐
相关产品推荐

