Why not recommended Date, but the use of Java8 new date and time API?

Java 8: The new date and time API

Before Java 8, all API on the time and date are flawed various aspects of the use, it is recommended to use the new date and time API, respectively, from the shortcomings of the old time and date of the API and solutions, Java 8 new time and date API to explain.

API defect of the old times and dates

Java's java.util.Date and java.util.Calendar class ease of use is poor, does not support time zone, and not thread safe.

Date if not format, print out the date of poor readability.

Thu Sep 12 13:47:34 CST 2019

SimpleDateFormat time may be used to format, but SimpleDateFormat is thread safe, SimpleDateFormat the source format methods as follows:

    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;
    }

Where the calendar is shared variables, and this shared variables do not thread-safe control. When multiple threads simultaneously using the same SimpleDateFormat objects [such as] a modified static SimpleDateFormat format when calling method, multiple threads can simultaneously call calendar.setTime method, a thread may have just set the time value of another thread immediately set time value to modify the format of time may result in the return is wrong.

Use SimpleDateFormat must be noted in multiple concurrent circumstances.

In addition to the format SimpleDateFormat is not thread-safe, parse method is thread safe. parse the actual method call alb.establish (calendar) .getTime () method to parse, alb.establish (calendar) method was mainly completed

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

But this is not a three-atomic operations, leading to parse out time can be wrong.

Date of time to deal with more trouble, such as want to get a year, a month, a week, and n days later time, if the Date to deal with the case so hard, and getYear Date class, getMonth these methods have been abandoned a.

How to ensure multi-threaded thread-safe

A SimpleDateFormat avoid sharing objects between threads, each thread is created using a SimpleDateFormat objects => large overhead of creating and destroying objects

For local use format and parse method for locking => poor blocking performance thread

Use ThreadLocal to ensure that each thread is created only once at most SimpleDateFormat objects => better way

Java 8 new time and date API

Date and time of Java class comprises 8 LocalDate, LocalTime, Instant, Duration and Period, these classes are included in the package java.time, 8 Java API new time of use, including the creation, formatting, resolution, calculation, modified , let's look at how to use.

LocalDate will only get date

// 创建 LocalDate
// 获取当前年月日
LocalDate localDate = LocalDate.now();
// 构造指定的年月日
LocalDate localDate1 = LocalDate.of(2019, 9, 12);
// 获取年、月、日、星期几
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 will only get minutes and seconds

// 创建 LocalTime
LocalTime localTime = LocalTime.of(14, 14, 14);
LocalTime localTime1 = LocalTime.now();
// 获取小时
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);

When LocalDateTime acquisition date, day, hour, equivalent to LocalDate + LocalTime

// 创建 LocalDateTime
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);
// 获取LocalDate
LocalDate localDate2 = localDateTime.toLocalDate();
// 获取LocalTime
LocalTime localTime2 = localDateTime.toLocalTime();

Instant acquiring seconds, for indicating a time stamp (accurate to nanoseconds)

If only to obtain the number of seconds or milliseconds, may be used System.currentTimeMillis ().

// 创建Instant对象
Instant instant = Instant.now();
// 获取秒数
long currentSecond = instant.getEpochSecond();
// 获取毫秒数
long currentMilli = instant.toEpochMilli();

Duration represents a period of time

// Duration.between()方法创建 Duration 对象
LocalDateTime from = LocalDateTime.of(2017, Month.JANUARY, 1, 00, 0, 0);    // 2017-01-01 00:00:00
LocalDateTime to = LocalDateTime.of(2019, Month.SEPTEMBER, 12, 14, 28, 0);     // 2019-09-15 14:28:00
Duration duration = Duration.between(from, to);     // 表示从 from 到 to 这段时间
long days = duration.toDays();              // 这段时间的总天数
long hours = duration.toHours();            // 这段时间的小时数
long minutes = duration.toMinutes();        // 这段时间的分钟数
long seconds = duration.getSeconds();       // 这段时间的秒数
long milliSeconds = duration.toMillis();    // 这段时间的毫秒数
long nanoSeconds = duration.toNanos();      // 这段时间的纳秒数

修改 LOCALDATE, localtime, localdateti to Instant.

LocalDate, LocalTime, LocalDateTime, Instant immutable objects, modify these objects will return a copy of the object.

Increase, decrease the number of years, the number of months, days, etc., in order to LocalDateTime example:

LocalDateTime localDateTime = LocalDateTime.of(2019, Month.SEPTEMBER, 12, 14, 32, 0);
// 增加一年
localDateTime = localDateTime.plusYears(1);
localDateTime = localDateTime.plus(1, ChronoUnit.YEARS);
// 减少一个月
localDateTime = localDateTime.minusMonths(1);
localDateTime = localDateTime.minus(1, ChronoUnit.MONTHS);  
// 通过with修改某些值
// 修改年为2020
localDateTime = localDateTime.withYear(2020);
localDateTime = localDateTime.with(ChronoField.YEAR, 2020);
// 时间计算
// 获取该年的第一天
LocalDate localDate = LocalDate.now();
LocalDate localDate1 = localDate.with(firstDayOfYear());

TemporalAdjusters contains many static methods can be called directly, the following are some examples:

Method name description
dayOfWeekInMonth Returns the day of the week in the same month
firstDayOfMonth Return to the first day of the month
firstDayOfNextMonth Returns the first day of next month
firstDayOfNextYear Return next year on the first day
firstDayOfYear The first day of this year's return
firstInMonth Return to the same month in the first day of the week
lastDayOfMonth Returns the last day of the month
lastDayOfNextMonth The last day to return next month
lastDayOfNextYear The last day to return next year
lastDayOfYear Returns the last day of the year
lastInMonth Return to the same month in the last week
next / previous After a return / before a given day of the week
nextOrSame / previousOrSame After a return / before a given day of the week, if the value meets the conditions for direct return

Formatting time

LocalDate localDate = LocalDate.of(2019, 9, 12);
String s1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
String s2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
// 自定义格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String s3 = localDate.format(dateTimeFormatter);

Resolution Time

LocalDate localDate1 = LocalDate.parse("20190912", DateTimeFormatter.BASIC_ISO_DATE);
LocalDate localDate2 = LocalDate.parse("2019-09-12", DateTimeFormatter.ISO_LOCAL_DATE);

to sum up

SimpleDateFormat and compared, DateTimeFormatter is thread-safe.

Instant higher accuracy, accurate to the nanosecond range.

Duration can easily obtain the number of days, number of hours period.

LocalDateTime able to quickly obtain year, month, day, for the next month and so on.

TemporalAdjusters class contains many useful static methods, avoid writing your own tools.

Guess you like

Origin www.cnblogs.com/wupeixuan/p/11511915.html