Java8 Date调整时间用法
Posted 大树叶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java8 Date调整时间用法相关的知识,希望对你有一定的参考价值。
Java8 Date调整时间用法
Date mydate=new Date();
String mydateStr=mydate.toInstant().atZone(ZoneId.systemDefault())
.toLocalDate().minusDays(1)
.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
下面是几个常用的用法
// 01. java.util.Date --> java.time.LocalDateTime
public void UDateToLocalDateTime()
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
// 02. java.util.Date --> java.time.LocalDate
public void UDateToLocalDate()
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
LocalDate localDate = localDateTime.toLocalDate();
// 03. java.util.Date --> java.time.LocalTime
public void UDateToLocalTime()
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
LocalTime localTime = localDateTime.toLocalTime();
// 04. java.time.LocalDateTime --> java.util.Date
public void LocalDateTimeToUdate()
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
// 05. java.time.LocalDate --> java.util.Date
public void LocalDateToUdate()
LocalDate localDate = LocalDate.now();
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
// 06. java.time.LocalTime --> java.util.Date
public void LocalTimeToUdate()
LocalTime localTime = LocalTime.now();
LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
//另外一个用法
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_MONTH, -1); //include current day
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
Date fromDate = cal.getTime();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
Date toDate = cal.getTime();
参考文档
- Date常用方法和相互时间调整。见这里的文章
以上是关于Java8 Date调整时间用法的主要内容,如果未能解决你的问题,请参考以下文章