Java8 LocalDateTime日常转换


/*LocalDateTime与时间戳互转*/
// LocalDateTime转时间戳
long timestamp = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println(String.format("timestamp => %s",timestamp));
// 时间戳转LocalDateTime
LocalDateTime now = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), TimeZone.getDefault().toZoneId());

/*LocalDateTime与指定格式时间日期字符串互转*/
// DateTimeFormatter.ISO_DATE相当于DateTimeFormatter.ofPattern("yyyy-MM-dd") 相应的还有DateTimeFormatter.ISO_DATE_TIME/DateTimeFormatter.ISO_TIME
format = now.format(DateTimeFormatter.ISO_DATE);
System.out.println(String.format("DateTimeFormatter.ISO_DATE => %s",format));
format = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println(String.format("'yyyy-MM-dd HH:mm:ss.SSS' => %s",format));
// 时间日期字符串转LocalDateTime
LocalDateTime parse = LocalDateTime.parse(format, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM