首先判断年份是否为闰年,再通过switch语句累加前几个月天数,最后加上当月日期得出当年第几天。例如2024年3月1日为第61天,因2024是闰年,2月有29天。

要计算指定日期是今年的第几天,可以使用 JavaScript 的 Date 对象结合 switch 语句来累加前面月份的天数。以下是实现方法:
首先从日期对象中提取年份和月份,并编写一个函数判断该年是否为闰年,因为2月的天数会受影响。
闰年规则:能被4整除且不能被100整除,或能被400整除。通过 switch 语句从1月开始向下穿透,逐个加上每个月的天数,直到目标月份的前一个月。
示例代码:
function getDayOfYear(year, month, day) {
// year: 年份,month: 1-12,day: 1-31
const isLeap = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
let totalDays = day;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">switch (month - 1) {
case 11: totalDays += 30; // 12月 -> 加11月
case 10: totalDays += 31; // 10月
case 9: totalDays += 30; // 9月
case 8: totalDays += 31; // 8月
case 7: totalDays += 31; // 7月
case 6: totalDays += 30; // 6月
case 5: totalDays += 31; // 5月
case 4: totalDays += 30; // 4月
case 3: totalDays += 31; // 3月
case 2: totalDays += 28 + (isLeap ? 1 : 0); // 2月(考虑闰年)
case 1: totalDays += 31; // 1月
}
return totalDays;}
比如计算 2024年3月1日 是当年第几天:
console.log(getDayOfYear(2024, 3, 1)); // 输出 61
因为2024是闰年,1月31天 + 2月29天 + 3月1天 = 61
这种方法利用 switch 的“穿透”特性,避免写多个 if 或数组查表,逻辑清晰且效率不错。
基本上就这些,不复杂但容易忽略闰年和月份边界问题。
以上就是js switch语句计算指定日期是今年的第几天的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号