1.时间转换
@Test
//LocalDateTime转long
public void java8TimeLocalTimeDateToLong(){
LocalDateTime now = LocalDateTime.now();
long milliLongTime= now.toInstant(ZoneOffset.of("+8")).toEpochMilli();//毫秒级
long secondLongTime= now.toInstant(ZoneOffset.of("+8")).getEpochSecond();//秒级
System.out.println(milliLongTime);
System.out.println(secondLongTime);
}
@Test
//long转LocalDateTime
public void Java8TimeLongToLocalTimeDate(){
long currTime =LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();;
LocalDateTime localDateTime= LocalDateTime.ofInstant(Instant.ofEpochMilli(currTime), TimeZone.getDefault().toZoneId());
System.out.println(localDateTime.toString());
}
@Test
//String转LocalDateTime
public void Java8TimeStingToLocalTimeDate(){
String timeStr="2021-05-04 21:12:10";
LocalDateTime stringTime= LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault()));
System.out.println(Locale.getDefault());
System.out.println(stringTime.toString());
}
@Test
//LocalDateTime转String
public void Java8TimeLocalTimeDateToString(){
LocalDateTime now = LocalDateTime.now();
String timeStr= now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
System.out.println(timeStr);
}
@Test
//LocalDateTime转java.util.Date
public void Java8TimeLocalTimeDateToDate(){
LocalDateTime now = LocalDateTime.now();
Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
System.out.println(date);
}
@Test
//java.util.Date转LocalDateTime
public void DateToJava8TimeLocalTimeDate(){
LocalDateTime ldt = new Date().toInstant()
.atZone( ZoneId.systemDefault() )
.toLocalDateTime();
System.out.println(ldt);
}
java 8 时间API
分享到: