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

如何使用Scala与JDK 8计算两个yyyyMM格式字符串日期的月份差

Hey,这个需求用JDK8的日期API搭配Scala来实现超简单,正好YearMonth类就是为这种只有年月的场景设计的,直接看实用方案:

计算yyyyMM格式日期的月份差值(Scala + JDK8)

完整可运行代码

import java.time.YearMonth
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

// 示例输入
val x = "201506"
val y = "201703"

// 定义匹配yyyyMM的格式化器
val dateFormatter = DateTimeFormatter.ofPattern("yyyyMM")

// 将字符串解析为YearMonth对象(自动校验日期合法性)
val startYearMonth = YearMonth.parse(x, dateFormatter)
val endYearMonth = YearMonth.parse(y, dateFormatter)

// 计算两个年月之间的月份差
val monthDifference = ChronoUnit.MONTHS.between(startYearMonth, endYearMonth)

println(monthDifference) // 输出:21

关键步骤解释

  • 解析字符串:用DateTimeFormatter.ofPattern("yyyyMM")定义格式,通过YearMonth.parse把输入的字符串转成YearMonth实例——如果输入的是像"202313"这种非法月份,会直接抛出异常,帮你做合法性校验。
  • 计算差值:ChronoUnit.MONTHS.between方法专门用来计算两个时间点的月份间隔,注意参数顺序是起始时间在前,结束时间在后,这样得到的就是正的差值;如果反过来,结果会是负数。
  • 结果验证:2015年6月到2017年3月,算下来正好是21个月,完全符合你的期望输出。

如果需要复用逻辑,可以封装成工具方法:

def getMonthDiff(startDateStr: String, endDateStr: String): Long = {
  val formatter = DateTimeFormatter.ofPattern("yyyyMM")
  val start = YearMonth.parse(startDateStr, formatter)
  val end = YearMonth.parse(endDateStr, formatter)
  ChronoUnit.MONTHS.between(start, end)
}

// 调用示例
println(getMonthDiff("201506", "201703")) // 输出:21

这样不管有多少组日期要计算,直接调用方法就行啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:42:33