Java8 LocalDateTime和Date相互转换
很想要用Java的时间api,但有时候还是需要转换为Date. 二者的相互转换并不是一步到位那么简单,所以,还是需要记录一下转换的api
Date to LocalDateTime
Date todayDate = new Date();
LocalDateTime ldt = todayDate.toInstant()
.atZone( ZoneId.systemDefault() )
.toLocalDateTime();
System.out.println(ldt);
//2019-05-16T19:22:12.773
LocalDateTime to Date
LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from( localDateTime.atZone( ZoneId.systemDefault()).toInstant());
System.out.println(date);
//Thu May 16 19:22:37 CST 2019
DateUtils
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateUtils {
public static Date asDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date asDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate asLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static LocalDateTime asLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
转自:https://www.cnblogs.com/woshimrf/p/LocalDateTime-to-Date.html
» 本文链接:https://blog.apires.cn/archives/2177.html
» 转载请注明来源:Java地带
» 《Java8 LocalDateTime和Date相互转换 》
» 本文章为Java地带整理创作,欢迎转载!转载请注明本文地址,谢谢!
» 部分内容收集整理自网络,如有侵权请联系我删除!
» 订阅本站:https://blog.apires.cn/feed/
评论已关闭