Java时间处理-LocalDateTime简介

时间:2022-07-28
本文章向大家介绍Java时间处理-LocalDateTime简介,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在项目开发过程中经常遇到日期时间处理,但是你真的用对了吗,理解阿里巴巴开发手册中禁用static修饰SimpleDateFormat吗

通过本篇文章将了解到

  • 为什么需要LocalDate、LocalTime、LocalDateTime(java8新提供的类)
  • java8新的时间API的使用方式,包括创建、格式化、解析、计算、修改

为什么需要LocalDate、LocalTime、LocalDateTime

  • Date如果不格式化,打印出的日期可读性差

Tue Oct 20 09:21:53 CST 2020

  • 使用SimpleDateFormat对时间进行格式化,但SimpleDateFormat是线程不安全的SimpleDateFormat的format方法最终调用代码:
// Called from Format after creating a FieldDelegate
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)方法里主要完成了

  • 重置日期对象cal的属性值
  • 使用calb中中属性设置cal
  • 返回设置好的cal对象

但是这三步不是原子操作

多线程并发如何保证线程安全

  • 避免线程之间共享一个SimpleDateFormat对象,每个线程使用时都创建一次SimpleDateFormat对象 => 创建和销毁对象的开销大
  • 对使用format和parse方法的地方进行加锁 => 线程阻塞性能差
  • 使用ThreadLocal保证每个线程最多只创建一次SimpleDateFormat对象 => 较好的方法

使用java8全新的日期和时间API

LocalDate
  • 创建LocalDate获取年、月、日、星期
// 获取当前年月日
LocalDate localDate = LocalDate.now();

// 构造指定的年月日
LocalDate localDate1 = LocalDate.of(2020,10,20);

// 获取年
int year = localDate.getYear();
int year1 = localDate.get(ChronoField.YEAR);

// 获取月
Month month = localDate.getMonth();
int month1 = localDate.get(ChronoField.MONTH_OF_YEAR);

// 获取日
int day = localDate.getDayOfMonth();
int day1 = localDate.get(ChronoField.DAY_OF_MONTH);

// 获取星期
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);
LocalTime
  • 创建LocalTime获取时、分、秒
// 获取当前时间
LocalTime localTime = LocalTime.now();
// 构造指定时间
LocalTime localTime1 = LocalTime.of(10,50,39);

// 获取小时
int hour = localTime.getHour();
int hour1 = localTime.get(ChronoField.HOUR_OF_DAY);

// 获取分
int minute = localTime.getMinute();
int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR);

// 获取秒
int second = localTime.getSecond();
int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE);
LocalDateTime
  • 创建LocalDateTime获取年月日时分秒
// 获取当前年月日时分秒
LocalDateTime localDateTime = LocalDateTime.now();

// 构造指定年月日时分秒
LocalDateTime localDateTime1 = LocalDateTime.of(2020,Month.OCTOBER,20,11,46,50);
LocalDateTime localDateTime2 = LocalDateTime.of(localDate,localTime);
LocalDateTime localDateTime3 = localDate.atTime(localTime);
LocalDateTime localDateTime4 = localTime.atDate(localDate);
使用Instant
// 创建Instant对象
Instant instant = Instant.now();

// 获取秒数
long currentSecond = instant.getEpochSecond();

// 获取毫秒数
long currentMilli = instant.toEpochMilli();

个人觉得如果只是为了获取秒数或者毫秒数,使用System.currentTimeMillis()来得更为方便;

修改LocalDate、LocalTime、LocalDateTime、Instant

LocalDate、LocalTime、LocalDateTime、Instant为不可变对象,修改这些对象对象会返回一个副本

  • 以LocalDateTime为例增加、减少年数、月数、天数等
// 获取当前年月日时分秒
LocalDateTime localDateTime = LocalDateTime.now();

// 增加一年
localDateTime = localDateTime.plusYears(1);
localDateTime = localDateTime.plus(1, ChronoUnit.YEARS);

// 减少一个月
localDateTime = localDateTime.minusMonths(1);
localDateTime = localDateTime.minus(1,ChronoUnit.MONTHS);

// 通过with方式修改某些值,修改年份为2022年,修改月日类似
localDateTime = localDateTime.withYear(2022);
localDateTime = localDateTime.with(ChronoField.YEAR,2022);
  • 格式化解析时间
// 获取当前年月日
LocalDate localDate = LocalDate.of(2020,10,20);
// 不带格式的输出,eg:20201020
String str1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);

// 自定义格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String str2 = localDate.format(dateTimeFormatter);

// 解析时间
LocalDate localDate1 = localDate.parse("20201020",DateTimeFormatter.BASIC_ISO_DATE);
LocalDate localDate2 = LocalDate.parse("2020-10-20", DateTimeFormatter.ISO_LOCAL_DATE);

和SimpleDateFormat相比,DateTimeFormatter是线程安全的

小结

Date有的LocalDateTime都有,Date没有的LocalDateTime也有,处理日期时间首选LocalDateTime。