如何列出当前月份的日期天数序列?示例:一月列1至31
列出当前月份所有日期天数的实现方法
下面提供几种主流编程语言的实现方式,直接生成当前月份从1到最后一天的连续数字列表:
Python 实现
利用datetime模块计算当前月份的最后一天,再生成数字序列:
import datetime today = datetime.date.today() current_year, current_month = today.year, today.month # 计算当月最后一天:下月1号减1天 if current_month == 12: last_day = datetime.date(current_year + 1, 1, 1) - datetime.timedelta(days=1) else: last_day = datetime.date(current_year, current_month + 1, 1) - datetime.timedelta(days=1) days_in_month = list(range(1, last_day.day + 1)) print(days_in_month)
Bash 实现
借助cal和seq命令快速生成:
# 获取当前月份的总天数 total_days=$(cal $(date +%m) $(date +%Y) | awk 'NF {last=$NF} END {print last}') # 输出1到总天数的连续数字 seq 1 $total_days
JavaScript 实现
通过Date对象的特性计算最后一天,再生成数组:
const now = new Date(); const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate(); const days = Array.from({ length: lastDay }, (_, index) => index + 1); console.log(days);
内容的提问来源于stack exchange,提问作者Awesome Lerman
相关产品推荐
相关产品推荐

