Pro, it is recommended that you use instead of Date oh LocalDateTime

In the project development process often encountered in processing time, but do you really use it right, please, understand Alibaba Developer's Handbook disable static modification SimpleDateFormat it

By reading this article you'll learn:

  • Why LocalDate, , LocalTime[java8LocalDateTime new offer classes]
  • java8The new time APIuse, including creating, formatting, parsing, calculate, modify

Why LocalDate, LocalTime, LocalDateTime

  • DateIf you do not format, print out the poor readability of date

    Tue Sep 10 09:34:04 CST 2019
    复制代码
  • Use SimpleDateFormattime format, but SimpleDateFormatis thread safe SimpleDateFormatthe formatmethod for final calling code:

    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;
        }
    复制代码

    calendarIt is a shared variable, and this shared variables do not thread-safe control. When multiple threads simultaneously using the same SimpleDateFormatobjects [such as a staticmodified SimpleDateFormat] calls formatupon the method, multiple threads can simultaneously call calendar.setTimemethod, a thread may have just set the timevalue of another thread immediately set the timevalue to modify the format of the result in the return of of time may be wrong. In the case of the use of multiple concurrent SimpleDateFormatneed extra attention SimpleDateFormatin addition to formatoutside are thread-unsafe parsemethods are thread safe. parseThe actual method calls the alb.establish(calendar).getTime()method to resolve, alb.establish(calendar)the method was mainly finished

      1. Cal property values ​​of target replacement date
      1. Using the attributes provided cal calb
      1. Back Set a good cal objects

But this is not a three-step atomic operation

How to ensure that multi-threaded thread-safe - Avoid sharing a thread between SimpleDateFormatobjects are created once each thread uses SimpleDateFormatthe object => large overhead of creating and destroying objects - use formatand parselocal methods for locking => poor blocking performance thread - use ThreadLocalto ensure that each thread created only once at most SimpleDateFormatobjects => better way

  • DateTime is too much trouble to deal with, such as want to get a year, a month, a week, and nafter days, if Dateto deal with the case so hard, you might say Dateclass is not there getYear, getMonththese methods do, get date very Easy, but they have been abandoned ah

Use java8 new date and time API together Come On

LocalDate

The date will only get

  • createLocalDate

    //获取当前年月日
    LocalDate localDate = LocalDate.now();
    //构造指定的年月日
    LocalDate localDate1 = LocalDate.of(2019, 9, 10);
    复制代码
  • Get year, month, date, day of the week

    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

You will only get a few minutes and seconds

  • createLocalTime

     LocalTime localTime = LocalTime.of(13, 51, 10);
     LocalTime localTime1 = LocalTime.now();
    复制代码
  • Get minutes and seconds

    //获取小时
    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.getMinute();
    int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE);
    复制代码
localdateti to

When the acquisition date, day, hour, equal to LocalDate + LocalTime

  • createLocalDateTime

    LocalDateTime localDateTime = LocalDateTime.now();
    LocalDateTime localDateTime1 = LocalDateTime.of(2019, Month.SEPTEMBER, 10, 14, 46, 56);
    LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);
    LocalDateTime localDateTime3 = localDate.atTime(localTime);
    LocalDateTime localDateTime4 = localTime.atDate(localDate);
    复制代码
  • ObtainLocalDate

     LocalDate localDate2 = localDateTime.toLocalDate();
    复制代码
  • ObtainLocalTime

    LocalTime localTime2 = localDateTime.toLocalTime();
    复制代码
Instant

Gets the number of seconds

  • Creating InstantObjects

    Instant instant = Instant.now();
    复制代码
  • Gets the number of seconds

    long currentSecond = instant.getEpochSecond();
    复制代码
  • Gets the number of milliseconds

    long currentMilli = instant.toEpochMilli();
    复制代码

Personally I feel that if only to get the number of seconds or milliseconds, use System.currentTimeMillis()is much more convenient

修改 LOCALDATE, localtime, localdateti to Instant

LocalDate, LocalTime, LocalDateTime, InstantAs immutable objects , to modify these objects objects will return a copy of the

  • Increase, decrease the number of years, months, days, etc. in order to LocalDateTime, for example
    LocalDateTime localDateTime = LocalDateTime.of(2019, Month.SEPTEMBER, 10,
                  14, 46, 56);
    //增加一年
    localDateTime = localDateTime.plusYears(1);
    localDateTime = localDateTime.plus(1, ChronoUnit.YEARS);
    //减少一个月
    localDateTime = localDateTime.minusMonths(1);
    localDateTime = localDateTime.minus(1, ChronoUnit.MONTHS);  
    复制代码
  • By withmodifying certain values
    //修改年为2019
    localDateTime = localDateTime.withYear(2020);
    //修改为2022
    localDateTime = localDateTime.with(ChronoField.YEAR, 2022);
    复制代码

You can also modify the month, day

Time calculation

For example, some want to know when the last day of this month is the date, next weekend is the date, you can quickly get an answer by providing time and date API

LocalDate localDate = LocalDate.now();
LocalDate localDate1 = localDate.with(firstDayOfYear());
复制代码

Such as by firstDayOfYear()return to the current date of the first day of the date, there are many ways not illustrated here

Formatting time
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);
复制代码

DateTimeFormatterThe default format offers a variety of ways, if not meet the requirements provided by default, through DateTimeFormatterthe ofPatternway to create a custom format mode

Resolution Time
LocalDate localDate1 = LocalDate.parse("20190910", DateTimeFormatter.BASIC_ISO_DATE);
LocalDate localDate2 = LocalDate.parse("2019-09-10", DateTimeFormatter.ISO_LOCAL_DATE);
复制代码

And SimpleDateFormatcompared, DateTimeFormatterare thread-safe

summary

LocalDateTime: DateSome I have, Dateno I have, please select the datePick Me

Guess you like

Origin juejin.im/post/5d7787625188252388753eae