Java8 日期/时间(Date Time)使用简介
特别说明: LocalDateTime 为日期时间的计算提供了很大的方便, 在构造对象/运算/toString等方便都非常便利。
3个常用的类:
java.time.LocalDateTime;
java.time.LocalDate;
java.time.LocalTime;
推荐多使用 LocalDateTime
常用表达式:
现在: LocalDateTime now = LocalDateTime.now();
今天: LocalDate today = LocalDate.now();
从属性创建对象:
LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
相互转换:
LocalDate date = localDateTime.toLocalDate(); LocalDateTime dateTime = localDate.atStartOfDay(); LocalTime time = localDateTime.toLocalTime(); LocalDateTime dateTime = localTime.atDate(localDate); LocalDateTime dateTime = LocalDateTime.of(date.getYear() + 1900, date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()); Date date = new Date(localDateTime.getYear() - 1900, localDateTime.getMonthValue() - 1, localDateTime.getDayOfMonth(), localDateTime.getHour(), localDateTime.getMinute(), localDateTime.getSecond()); //会丢失 nanoOfSecond
组件兼容性:
- myBatis (mybatis-spring v1.3.0) 暂不支持 localDateTime
- Json (com.fasterxml.jackson.core v2.5.4) 貌似也没特别的支持, 序列化的结果如下:
{ "month": "DECEMBER", "year": 2017, "dayOfMonth": 7, "dayOfWeek": "THURSDAY", "dayOfYear": 341, "monthValue": 12, "hour": 10, "minute": 4, "nano": 228000000, "second": 58, "chronology": { "id": "ISO", "calendarType": "iso8601" } }
所以, 在与 数据库 交互, 与 Json 交互时还是建议使用 java.util.Date
总结:
当前情况下, 业务计算建议使用 LocalDateTime, 业务计算以外建议转化为 Date
By the way:
LocalDateTime 为日期时间的计算提供了很大的方便, 还有诸多其它优点。详细内容 Java8 日期/时间(Date Time)API指南](http://www.importnew.com/14140.html
博主简介:佘焕敏(shé),洋名 Billy Sir。
关注编程基础技术,并致力于研究软件的自动化生成。 对编程规范化、面向对象的极致使用也有着浓厚的兴趣。 同时非常希望能够写程序到65岁。
只有工匠精神,才能把常人觉得单调乏味的代码,当作作品雕刻成艺术品。
重点:这里几乎每一篇文章,都是我认真创作的,凝结了心血。写作从来都不是一件容易的事,对从小语文不好的我而言,是难上加难。而且,你发现没有,文中没有广告。这篇文章介绍了为什么要写这些文章。

【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性