由于java版本的迭代,一个使用java开发的项目中可能出现多种日期对象,例如LocalDateTime、LocalDate、Date,不像C#只有一个DateTime,因此在各种日期格式或者对象之间的转换显得有点复杂,总是记不住,在需要用到时总是需要依靠搜索引擎,有点浪费时间,所以特意把常用的转换场景总结如下:
1、 LocalDateTime转为String、TimeStamp、Long、Instant、 Date
System.out.println("----------------LocalDateTime----------------"); //LocalDateTime -> String String localDateTimeToString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); System.out.println("LocalDateTime -> String: " + localDateTimeToString); //LocalDateTime -> TimeStamp Timestamp localDateTimeToTimeStamp = Timestamp.valueOf(LocalDateTime.now()); System.out.println("LocalDateTime -> TimeStamp: " + localDateTimeToTimeStamp); //LocalDateTime -> Long Long localDateTimeToLong = Timestamp.valueOf(LocalDateTime.now()).getTime(); System.out.println("LocalDateTime -> Long: " + localDateTimeToLong); //LocalDateTime -> Instant Instant localDateTimeToInstant = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant(); System.out.println("LocalDateTime -> Instant: " + localDateTimeToInstant); //LocalDateTime -> Date Date LocalDateTimeToDate = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()); System.out.println("LocalDateTime -> Date: " + LocalDateTimeToDate);