1.首先:
為什么使用LocalDate、LocalTime、LocalDateTime而不是Date
https://juejin.im/post/5d7787625188252388753eae
一句話總結還是因為SimpleDateFormat的線程安全問題
2.如何學習LocalDate、LocalTime、LocalDateTime 三者都是java8全新的日期和時間API
二:通常第一個需求就是獲取年月日以及星期幾
2.1 LocalDate
首先是創建LocalDate:
//獲取當前年月日
LocalDate localDate = LocalDate.now();
//構造指定的年月日
LocalDate localDate1 = LocalDate.of(2019, 9, 10);
其次是獲取指定日期的年、月、日:
年
2.2 LocalTime
首先是獲取LocalTime
LocalTime localTime1 = LocalTime.now();
LocalTime localTime = LocalTime.of(13, 51, 10);
其次是獲取時分秒:
通過LocalDateTime來獲取LocalDate
獲取毫秒數:
long currentMilli = instant.toEpochMilli();
如果只是為了獲取秒數或者毫秒數,使用System.currentTimeMillis()
來得更為方便
二:第二個需求就是對獲取的年月日小時分鍾秒等進行加減操作
LocalDate
、LocalTime
、LocalDateTime
、Instant
為不可變對象,修改這些對象對象會返回一個副本
增加、減少年數、月數、天數等 以LocalDateTime
為例
firstDayOfYear()
返回了當前日期的第一天日期,還有很多方法這里不在舉例說明
LocalDate localDate = LocalDate.of(2019, 9, 10); String s1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE); String s2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE); //自定義格式化 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String s3 = localDate.format(dateTimeFormatter); 復制代碼
DateTimeFormatter
默認提供了多種格式化方式,如果默認提供的不能滿足要求,可以通過DateTimeFormatter
的ofPattern
方法創建自定義格式化方式
五. 第五個需求,解析時間:
public static LocalDateTime getDayByYearMonth(int year,int month,String opr) { LocalDate localDate = LocalDate.now(); LocalDate withlocalDate = localDate.withYear(year).withMonth(month); if("F".equals(opr)) { return LocalDateTime.of(withlocalDate.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN); } return LocalDateTime.of(withlocalDate.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MIN); } public static LocalDateTime getDayByDate(LocalDateTime date,String opr) { if("F".equals(opr)) { return LocalDateTime.of(date.toLocalDate(), LocalTime.MIN); } return LocalDateTime.of(date.toLocalDate(), LocalTime.MAX); }
SimpleDateFormat
相比,DateTimeFormatter
是線程安全的
- 將LocalDateTime字段以時間戳的方式返回給前端
添加日期轉化類
並在public class LocalDateTimeConverter extends JsonSerializer<LocalDateTime> { @Override public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeNumber(value.toInstant(ZoneOffset.of("+8")).toEpochMilli()); } }
LocalDateTime
字段上添加@JsonSerialize(using = LocalDateTimeConverter.class)
注解,如下:@JsonSerialize(using = LocalDateTimeConverter.class) protected LocalDateTime gmtModified;
- 將LocalDateTime字段以指定格式化日期的方式返回給前端
在LocalDateTime
字段上添加@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
注解即可,如下:@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss") protected LocalDateTime gmtModified;
- 對前端傳入的日期進行格式化
在LocalDateTime
字段上添加@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
注解即可,如下:@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") protected LocalDateTime gmtModified;