Java LocalDateTime 入门
在Java 8中,日期和时间的处理发生了很大变化。Java 8之前,我们使用java.util.Date
和java.util.Calendar
来处理日期和时间。这些API存在诸多问题,比如时区处理上的问题,API的设计也不太友好。
为了解决这些问题,Java 8引入了全新的日期和时间API,其中LocalDateTime
是其中一个重要的类。
创建LocalDateTime对象
我们可以使用LocalDateTime.now()
获取当前本地日期时间:
LocalDateTime now = LocalDateTime.now();
也可以使用指定的年月日时分秒创建LocalDateTime
对象:
LocalDateTime ldt = LocalDateTime.of(2020, 01, 25, 12, 30, 50);
获取日期时间信息
可以分别获取LocalDateTime
对象中的年、月、日、时、分、秒信息:
int year = ldt.getYear(); //2020
Month month = ldt.getMonth(); //JANUARY
int day = ldt.getDayOfMonth(); //25
int hour = ldt.getHour(); //12
int minute = ldt.getMinute(); //30
int second = ldt.getSecond();//50
也可以用更方便的get()
方法获取:
int year = ldt.get(ChronoField.YEAR);
int month = ldt.get(ChronoField.MONTH_OF_YEAR);
int day = ldt.get(ChronoField.DAY_OF_MONTH);
时间计算
我们可以方便的对LocalDateTime
对象进行时间计算:
//加一天
LocalDateTime tomorrow = ldt.plusDays(1);
//减一小时
LocalDateTime beforeOneHour = ldt.minusHours(1);
//加两月
LocalDateTime afterTwoMonths = ldt.plusMonths(2);
该类提供了大量时间计算的方法,可以加/减年、月、日、时、分、秒等。
格式化和解析
我们可以使用DateTimeFormatter
来格式化和解析LocalDateTime
对象。例如:
//格式化
String formatDateTime = ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//解析
LocalDateTime parseDateTime = LocalDateTime.parse("2023-04-01 12:30:50", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
时间戳
可以使用toEpochSecond()
方法获取LocalDateTime
对象对应的时间戳(从1970-01-01T00:00:00Z UTC开始的秒数)
long ts = ldt.toEpochSecond(ZoneOffset.ofHours(8));
//时间戳,加上8小时时差
也可以使用toInstant()
方法获取Instant
对象,然后由Instant
对象获取时间戳:
Instant instant = ldt.toInstant(ZoneOffset.ofHours(8));
long ts = instant.getEpochSecond();
时区转换
LocalDateTime是本地日期时间,不带时区信息。我们可以使用atZone()
方法将其转换为带时区的ZonedDateTime
对象。例如:
//东八区
ZonedDateTime zdt = ldt.atZone(ZoneId.of("Asia/Shanghai"));
//UTC时区
ZonedDateTime zdtUtc = ldt.atZone(ZoneId.of("UTC"));
然后可以通过ZonedDateTime
对象输出不同时区的日期时间,或进行时区之间的转换等操作。
与Date互操作
我们可以通过toInstant()
方法获取Instant
对象,然后由Instant
对象得到Date
对象:
Instant instant = ldt.toInstant(ZoneId.systemDefault());
Date legacyDate = Date.from(instant);
也可以由Date
对象得到LocalDateTime
:
Instant instant = legacyDate.toInstant();
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
修改日期时间
我们可以使用withXxx()
方法修改LocalDateTime
对象的某个时间字段,创建一个新的LocalDateTime
对象。例如:
//设置为10月20日
LocalDateTime date2 = ldt.withMonth(10).withDayOfMonth(20);
//设置为15时30分
LocalDateTime time2 = ldt.withHour(15).withMinute(30);
也可以直接使用plusXxx()
/minusXxx()方法修改,返回新对象:
//加一天
LocalDateTime date3 = ldt.plusDays(1);
//减一小时
LocalDateTime time3 = ldt.minusHours(1);
判断两个LocalDateTime对象
我们可以使用isAfter()
,isBefore()或isEqual()
方法判断两个LocalDateTime
对象的时间先后关系。
LocalDateTime ldt2 = LocalDateTime.of(2020, 01, 26, 15, 30);
boolean after = ldt.isAfter(ldt2); //false
boolean before = ldt.isBefore(ldt2); //true
boolean equal = ldt.isEqual(ldt2); //false
希望这些内容能对大家理解LocalDateTime
有更深入的认识。