Java8的日期时间处理
代码:
package com.ufo.java8datetime; import java.time.Clock; import java.time.LocalDate; import java.time.LocalTime; import java.time.Period; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class Java8DateTime { public static void main(String[] args) { // 取今天日期 LocalDate today=LocalDate.now(); System.out.println("Today's date="+today); System.out.println("Today's year="+today.getYear()); System.out.println("Today's month="+today.getMonthValue()); System.out.println("Today's day="+today.getDayOfMonth()); // 特定日期 LocalDate devoiceDay=LocalDate.of(2020, 1, 16); System.out.println("Devoice date="+devoiceDay); // 日期相等比较 if(today.equals(devoiceDay)==false) { System.out.println("today !=devoiceDay "); } // 一周后 LocalDate aWeekLater=today.plus(1, ChronoUnit.WEEKS); System.out.println("A week later="+aWeekLater); // 一年前 LocalDate aYearBefore=today.plus(-1, ChronoUnit.YEARS); System.out.println("A Year before="+aYearBefore); // 日期比较 LocalDate longAgo=LocalDate.of(2000, 1, 1); if(longAgo.isBefore(aYearBefore)) { System.out.println(longAgo+" is before "+aYearBefore); } // 日期比较 if(today.isAfter(aYearBefore)) { System.out.println(today+" is after "+aYearBefore); } // 年份差 Period years=Period.between(longAgo, aYearBefore); System.out.println("There are "+years.getYears()+" years between "+longAgo+" "+aYearBefore); // 当前时间 LocalTime currTime=LocalTime.now(); System.out.println("Current time="+currTime); // 时间加 LocalTime threehoursLater=currTime.plusHours(3); System.out.println("3 hours later="+threehoursLater); // 取毫秒时间戳 Clock clock=Clock.systemUTC(); System.out.println(clock.millis()+" == "+System.currentTimeMillis()); // 日期转字符串 DateTimeFormatter format1=DateTimeFormatter.ofPattern("yyyy年MM月dd日"); System.out.println(today.format(format1)); // 字符串转日期 LocalDate date1=LocalDate.parse("1644年03月14日", format1); System.out.println(date1); } }
输出:
Today's date=2020-01-20 Today's year=2020 Today's month=1 Today's day=20 Devoice date=2020-01-16 today !=devoiceDay A week later=2020-01-27 A Year before=2019-01-20 2000-01-01 is before 2019-01-20 2020-01-20 is after 2019-01-20 There are 19 years between 2000-01-01 2019-01-20 Current time=20:40:57.528 3 hours later=23:40:57.528 1579524057528 == 1579524057528 2020年01月20日 1644-03-14
2020年1月20日
分类:
Java.日期时间处理
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2017-01-20 【Canvas与艺术】红色3号桌球
2014-01-20 查看CentOs6.5/7的系统版本号
2014-01-20 【Canvas技法】绘制圆角多边形