LocalDate和localDateTime常用方法


public class TestTime extends TestCase {
    private static final Logger log = LoggerFactory.getLogger(TestLocalDate.class);
    public void testDate() {
        //創建LocalDate,只會獲取年月日
        //獲取當前年月日
        LocalDate localDate = LocalDate.now();
        //構造指定的年月日
        LocalDate specifiedDate = LocalDate.of(2019, 2, 19);
        //年
        int year = specifiedDate.getYear(); //2019
        int year1 = specifiedDate.get(ChronoField.YEAR); //2019
        //月
        Month month = specifiedDate.getMonth();  //FEBRUARY
        int month1 = specifiedDate.get(ChronoField.MONTH_OF_YEAR); //2
        //日
        int day = specifiedDate.getDayOfMonth(); //19
        int day1 = specifiedDate.get(ChronoField.DAY_OF_MONTH); //19
        //星期幾
        DayOfWeek dayOfWeek = specifiedDate.getDayOfWeek(); //TUESDAY
        int dayOfWeek1 = specifiedDate.get(ChronoField.DAY_OF_WEEK); //2

        //創建LocalTime,只會獲取幾時幾分幾秒
        LocalTime localTime = LocalTime.now();
        //構造指定LocalTime
        LocalTime specifiedTime = LocalTime.of(8, 18, 28);
        //獲取小時
        int hour = specifiedTime.getHour(); //8
        int hour1 = specifiedTime.get(ChronoField.HOUR_OF_DAY);  //8
        //獲取分
        int minute = specifiedTime.getMinute(); //18
        int minute1 = specifiedTime.get(ChronoField.MINUTE_OF_HOUR); //18

        //創建LocalDateTime,獲取年月日時分秒,等於LocalDate+LocalTime
        LocalDateTime localDateTime = LocalDateTime.now(); //now
        LocalDateTime specifiedTimeLocalDateTime = LocalDateTime.of(2019, Month.FEBRUARY, 19, 8, 18, 28); //2019-02-19T08:18:28
        LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime); //now
        LocalDateTime localDateTime3 = localDate.atTime(localTime); //now
        LocalDateTime localDateTime4 = localTime.atDate(localDate); //now

        log.info("{},{},{},{},{}", localDateTime, specifiedTimeLocalDateTime, localDateTime2, localDateTime3, localDateTime4);
        //獲取LocalDate
        specifiedTimeLocalDateTime.toLocalDate(); //2019-02-19
        //獲取LocalTime
        specifiedTimeLocalDateTime.toLocalTime(); //08:18:28

        //創建 Instant 對象 是不帶時區的即時時間點
        Instant instant = Instant.now(); //2020-04-23T06:58:21.651Z
        //獲取秒數
        long currentSecond = instant.getEpochSecond(); //1587625101
        //獲取毫秒數
        long currentMilli = instant.toEpochMilli(); //1587625101651

        //修改LocalDate、LocalTime、LocalDateTime、Instant
        //LocalDate 、 LocalTime 、 LocalDateTime 、 Instant 為不可變對象,修改這些對象對象會返回一個副本
        LocalDateTime localDateTime5 = LocalDateTime.of(2019, Month.SEPTEMBER, 10, 14, 46, 56); //2019-09-10T14:46:56
        //增加一年
        localDateTime5 = localDateTime5.plusYears(1); //2020-09-10T14:46:56
        localDateTime5 = localDateTime5.plus(1, ChronoUnit.YEARS); //2021-09-10T14:46:56
        //減少一個月
        localDateTime5 = localDateTime5.minusMonths(1); //2021-08-10T14:46:56
        localDateTime5 = localDateTime5.minus(1, ChronoUnit.MONTHS); //2021-07-10T14:46:56

        //通過with修改某些值
        //修改年為2020
        localDateTime = localDateTime.withYear(2020); //2020-04-23T15:00:55.751
        //修改為2022
        localDateTime = localDateTime.with(ChronoField.YEAR, 2022); //2022-04-23T15:00:55.751

        //時間計算
        //比如有些時候想知道這個月的最后一天是幾號、下個周末是幾號,通過提供的時間和日期API可以很快得到答案
        LocalDate localDate3 = LocalDate.now();
        //第一天
        LocalDate f = localDate3.with(firstDayOfMonth());   //2020-04-01

        //格式化時間
        LocalDate localDate4 = LocalDate.of(2019, 9, 10);
        String s1 = localDate4.format(DateTimeFormatter.BASIC_ISO_DATE);   //20190910
        String s2 = localDate4.format(DateTimeFormatter.ISO_LOCAL_DATE);   //2019-09-10

        String s = localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE); //2022-04-23

        //DateTimeFormatter 默認提供了多種格式化方式,如果默認提供的不能滿足要求,可以通過
        //DateTimeFormatter 的 ofPattern 方法創建自定義格式化方式
        String s3 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm")); //2022-04-23 03:00

        //解析時間
        LocalDate localDate5 = LocalDate.parse("20190910", DateTimeFormatter.BASIC_ISO_DATE);  //2019-09-10
        LocalDate localDate6 = LocalDate.parse("2019-09-10", DateTimeFormatter.ISO_LOCAL_DATE); //2019-09-10
    }
}

項目應用LocalDateTime

  • 將LocalDateTime字段以時間戳的方式返回給前端

添加日期轉化類

public class LocalDateTimeConverter extends JsonSerializer<LocalDateTime> {
    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializer) throws IOException {
        gen.writeNumber(value.toInstant(ZoneOffset.of("+8")).toEpochMilli());
    }
}

並在 LocalDateTime 字段上添加 @JsonSerialize(using = LocalDateTimeConverter.class) 注解,
如下:

    @JsonSerialize(using = LocalDateTimeConverter.class)
    private LocalDateTime day;
  • 將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")
    private LocalDateTime register;
  • 對前端傳入的日期進行格式化

在 LocalDateTime 字段上添加 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 注解即可,如下:

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime login;

與原來Date類對比優勢

  • Date如果不格式化,打印出的日期可讀性差
  • 使用SimpleDateFormat對時間進行格式化,但SimpleDateFormat是線程不安全的

SimpleDateFormatformat方法最終調用代碼:

private StringBuffer format(Date date, StringBuffer toAppendTo,
                              FieldDelegate delegate) {
        // Convert input date to time field list
        calendar.setTime(date);

        boolean useDateFormatSymbols = useDateFormatSymbols();

        for (int i = 0; i < compiledPattern.length; ) {
            int tag = compiledPattern[i] >>> 8;
            int count = compiledPattern[i++] & 0xff;
            if (count == 255) {
                count = compiledPattern[i++] << 16;
                count |= compiledPattern[i++];
            }

            switch (tag) {
            case TAG_QUOTE_ASCII_CHAR:
                toAppendTo.append((char)count);
                break;

            case TAG_QUOTE_CHARS:
                toAppendTo.append(compiledPattern, i, count);
                i += count;
                break;

            default:
                subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
                break;
            }
        }
        return toAppendTo;
    }
  可以看到,calendar是共享變量,並且這個共享變量沒有做線程安全控制。當多個線程同時使用相同的SimpleDateFormat對象【如用static修飾的SimpleDateFormat】調用format方法時,多個線程會同時調用calendar.setTime方法,可能一個線程剛設置好time值另外的一個線程馬上把設置的time值給修改了導致返回的格式化時間可能是錯誤的。在多並發情況下使用SimpleDateFormat需格外注意SimpleDateFormat除了format是線程不安全以外,parse方法也是線程不安全的。parse方法實際調用alb.establish(calendar).getTime()方法來解析,alb.establish(calendar)方法里主要完成了:
  1. 重置日期對象cal的屬性值
  2. 使用calb中中屬性設置cal
  3. 返回設置好的cal對象

但是這三步不是原子操作

  多線程並發如何保證線程安全 - 避免線程之間共享一個SimpleDateFormat對象,每個線程使用時都創建一次SimpleDateFormat對象 => 創建和銷毀對象的開銷大 - 對使用formatparse方法的地方進行加鎖 => 線程阻塞性能差 - 使用ThreadLocal保證每個線程最多只創建一次SimpleDateFormat對象 => 較好的方法

  • Date對時間處理比較麻煩,比如想獲取某年、某月、某星期,以及n天以后的時間,如果用Date來處理是很麻煩的,雖然Date類有getYeargetMonth這些方但都已經被棄用

 

原文


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM