java.util.Date and jdk1.8 new time API Competition

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

1. Reset the date attribute value of the object cal
2. calb cal set in the attribute
3. Back-set cal objects
but this is not a three-atomic operation, resulting in the parsed time may 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(2019912);
// 获取年、月、日、星期几
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(141414);
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, 10144656);
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, 10000);    // 2017-01-01 00:00:00
LocalDateTime to = LocalDateTime.of(2019, Month.SEPTEMBER, 1214280);     // 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, 1214320);
// 增加一年
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
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

Demonstrate what usage

// 当前时间为2019-09-01 11:17:24

// 2019-09-01
LocalDate.now().with(TemporalAdjusters .firstDayOfMonth());
// 2019-01-01T11:17:24.070
LocalDateTime.now().with(TemporalAdjusters .firstDayOfYear());

Formatting time

LocalDate localDate = LocalDate.of(2019912);
String s1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
String s2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
// 自定义格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
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

1. SimpleDateFormat and compared, DateTimeFormatter is thread-safe.
2.Instant higher accuracy and to be accurate to the nanosecond range.
3.Duration can easily obtain the number of days, number of hours period.
4.LocalDateTime able to quickly obtain year, month, day, for the next month and so on.
5.TemporalAdjusters class contains many useful static methods, avoid writing your own tools.

Guess you like

Origin www.cnblogs.com/HHR-SUN/p/11566234.html