You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言使用lubridate统计不同日期间隔内的闰日数量

R语言lubridate包实现日期间隔内闰日数量统计方案

首先加载依赖包:

library(lubridate)

核心自定义函数

直接通过校验每个闰年的2月29日是否落在目标区间内完成统计,逻辑清晰无边界问题:

count_leap_days <- function(start_date, end_date) {
  # 统一转换为日期格式,兼容字符串输入
  start_date <- as.Date(start_date)
  end_date <- as.Date(end_date)
  # 提取区间覆盖的所有年份
  start_y <- year(start_date)
  end_y <- year(end_date)
  all_years <- seq(start_y, end_y)
  # 筛选所有闰年
  leap_years <- all_years[leap_year(all_years)]
  if (length(leap_years) == 0) return(0)
  # 生成所有闰年的2月29日
  feb29_dates <- ymd(paste0(leap_years, "-02-29"))
  # 统计落在区间内的2月29日数量
  sum(feb29_dates >= start_date & feb29_dates <= end_date)
}

测试用例验证

# 你提供的示例
start_date <- as.Date("2008-03-31")
end_date <- as.Date("2020-09-30")
count_leap_days(start_date, end_date)
# 输出结果为3,符合预期

批量处理方案

如果需要批量计算多组区间的闰日数,假设你有存储起止日期的数据框:

# 示例数据框
date_df <- data.frame(
  start = c("2008-03-31", "2019-01-01", "2020-02-28", "2020-03-01"),
  end = c("2020-09-30", "2021-12-31", "2020-03-01", "2021-01-01")
)
# 批量计算,新增结果列
date_df$leap_day_count <- mapply(count_leap_days, date_df$start, date_df$end)

运行后date_df的leap_day_count列会依次输出3,2,1,0,覆盖了所有边界场景。

内容的提问来源于stack exchange,提问作者Wahoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:57:04