Java 计算两个日期相差多少年月日
JDK7及以前的版本,计算两个日期相差的年月日比较麻烦。
JDK8新出的日期类,提供了比较简单的实现方法。
/** * 计算2个日期之间相差的 相差多少年月日 * 比如:2011-02-02 到 2017-03-02 相差 6年,1个月,0天 * @param fromDate YYYY-MM-DD * @param toDate YYYY-MM-DD * @return 年,月,日 例如 1,1,1 */ public static String dayComparePrecise(String fromDate, String toDate){ Period period = Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate)); StringBuffer sb = new StringBuffer(); sb.append(period.getYears()).append(",") .append(period.getMonths()).append(",") .append(period.getDays()); return sb.toString(); }
一个简单的工具方法,供参考。
简要说2点:
1. LocalDate.parse(dateString) 这个是将字符串类型的日期转化为LocalDate类型的日期,默认是DateTimeFormatter.ISO_LOCAL_DATE即YYYY-MM-DD。
LocalDate还有个方法是parse(CharSequence text, DateTimeFormatter formatter),带日期格式参数,下面是JDK中的源码,比较简单,不多说了,感兴趣的可以自己去看一下源码
/** * Obtains an instance of {@code LocalDate} from a text string using a specific formatter. * <p> * The text is parsed using the formatter, returning a date. * * @param text the text to parse, not null * @param formatter the formatter to use, not null * @return the parsed local date, not null * @throws DateTimeParseException if the text cannot be parsed */ public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) { Objects.requireNonNull(formatter, "formatter"); return formatter.parse(text, LocalDate::from); }
2. 利用Period计算时间差,Period类内置了很多日期计算方法,感兴趣的可以去看源码。Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));主要也是用LocalDate去做计算。Period可以快速取出年月日等数据。
3. 使用旧的Date
对象时,我们用SimpleDateFormat
进行格式化显示。使用新的LocalDateTime
或ZonedLocalDateTime
时,我们要进行格式化显示,就要使用DateTimeFormatter
。
和SimpleDateFormat
不同的是,DateTimeFormatter
不但是不变对象,它还是线程安全的。线程的概念我们会在后面涉及到。现在我们只需要记住:因为SimpleDateFormat
不是线程安全的,使用的时候,只能在方法内部创建新的局部变量。而DateTimeFormatter
可以只创建一个实例,到处引用。
创建DateTimeFormatter
时,我们仍然通过传入格式化字符串实现:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
格式化字符串的使用方式与SimpleDateFormat
完全一致。
参考: https://blog.csdn.net/francislpx/article/details/88691386
https://www.liaoxuefeng.com/wiki/1252599548343744/1303985694703650
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义