本文是依據網絡文章進行的彙總,持續更新帖
爲何要學 Java 8 的日期時間方法呢?SimpleDateFormat 不是很好用嗎?我相信這種聲音不在少數,緣由有:java
Long millisecond = Instant.now().toEpochMilli(); // 精確到毫秒 Long second = Instant.now().getEpochSecond();// 精確到秒
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time),ZoneId.systemDefault()));
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime parse = LocalDateTime.parse("2018-05-29 13:52:50", ftf); LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
//將java.util.Date 轉換爲java8 的java.time.LocalDateTime,默認時區爲東8區 public static LocalDateTime dateConvertToLocalDateTime(Date date) { return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime(); } //將java8 的 java.time.LocalDateTime 轉換爲 java.util.Date,默認時區爲東8區 public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) { return Date.from(localDateTime.toInstant(ZoneOffset.of("+8"))); }
/** * 取本月第一天 */ public static LocalDate firstDayOfThisMonth() { LocalDate today = LocalDate.now(); return today.with(TemporalAdjusters.firstDayOfMonth()); } /** * 取本月第N天 */ public static LocalDate dayOfThisMonth(int n) { LocalDate today = LocalDate.now(); return today.withDayOfMonth(n); } /** * 取本月最後一天 */ public static LocalDate lastDayOfThisMonth() { LocalDate today = LocalDate.now(); return today.with(TemporalAdjusters.lastDayOfMonth()); } /** * 取本月第一天的開始時間 */ public static LocalDateTime startOfThisMonth() { return LocalDateTime.of(firstDayOfThisMonth(), LocalTime.MIN); } /** * 取本月最後一天的結束時間 */ public static LocalDateTime endOfThisMonth() { return LocalDateTime.of(lastDayOfThisMonth(), LocalTime.MAX);
Java8 LocalDateTime獲取時間戳(毫秒/秒)、LocalDateTime與String互轉、Date與LocalDateTime互轉網絡