Jdk1.8 time processing

The article has been synchronized to Github:https://github.com/stackInk/makerstack

1. Traditional time issues

1.1 SimpleDateFormat in multithreaded environment

When multiple threads at the same time processing object to date format, there will be a Java lang. A NumberFormatException: multiple points. The main reason is that SimpleDateFormat is thread-unsafe and raises this exception when shared by threads.

1.1.1 Code demonstration

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
// Threads in the thread pool share SimpleDateFormat, raising threads is not safe
Callable<String> callable = () -> simpleDateFormat.parse("20200402").toString();

ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Future<String>> list = new LinkedList<>();  for (int i = 0; i < 10; i++) {  Future<String> submit = executorService.submit(callable);  list.add(submit); } for (Future<String> stringFuture : list) {  String s = stringFuture.get();  System.out.println(s); } executorService.shutdown(); Copy the code

Solutions:

  • Threads do not share variablesSimpleDateFormatEach thread creates its own when formatting the date
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Future<String>> list = new LinkedList<>();
for (int i = 0; i < 10; i++) {
   Future<String> submit = executorService.submit(new MyCallable01("20200403"));
   list.add(submit);
} for (Future<String> stringFuture : list) {  String s = stringFuture.get();  System.out.println(s);  } executorService.shutdown();  class MyCallable01 implements Callable<String>{   private String date ;   public MyCallable01(String date) {  this.date = date;  }   @Override  public String call(a) throws Exception {  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");  return simpleDateFormat.parse(date).toString();  } } Copy the code
  • throughThreadLocalBind one for each threadSimpleDateFormate
Future<String> submit = executorService.submit(() -> ResolveByThreadLocal.converDateStrToDate("20200405"));

public class ResolveByThreadLocal {
    // Create a ThreadLocal that binds each variable
    private static final ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<>();
  public static String converDateStrToDate(String date) throws ParseException {  SimpleDateFormat simpleDateFormat = threadLocal.get(); ;  if(simpleDateFormat == null) { simpleDateFormat = new SimpleDateFormat("yyyyMMdd");  threadLocal.set(simpleDateFormat);  }  Date parse = simpleDateFormat.parse(date);  return parse.toString() ;  } }  Copy the code

2. 1.8 Time processing

The handling of time is in the java.time package and its subpackages, and is thread-safe


  • java.timeThe various classes for time processing are stored under the package
    • InstantGets the timestamp of the local time
    • LocalDateGets the date of the local time
    • LocalTimeGets the time of the local time
    • LocalDateTimeGets the date and time of the local time
    • DurationCalculates the interval between two dates
    • PeriodCalculate the interval between the two times
    • OffsetDateTimeOffsets date and time calculations
    • offsetTimeCalculate the offset of time
    • ZoneIdVarious time zone codes
    • ZoneOffsetUrban offset calculation
    • ZonedDateTime
  • java.time.chronoDifferent ways of keeping time in different areas
  • java.time.temporalMake some adjustments to the time package
  • java.time.formatFormat the time

2.1 LocalDate, LocalTime, and LocalDateTime

The three are used in exactly the same way, the output results are different

  • nowGet local time
LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        System.out.println(now.getYear());
        System.out.println(now.getMonthValue());// Get the month directly
        System.out.println(now.getDayOfMonth());
 System.out.println(now.getHour());  System.out.println(now.getMinute());  System.out.println(now.getSecond());  Output:2020-04-03T10:25:29.906 2020 4 3 10 25 29 Copy the code
  • of()Pass in the specified date and time

  • Add offset to time

  • Offsets the event

  • A comparison of the current time with another time

  • Modifies the number of days in a month, year, month, etc. to the specified value, and returns a new oneLocalDateTimeobject

  • getmethods

  • format(DateTimeFormatter formatter)Format the date
  • untilReturns the value between two datesPeriodobject
  • isLeapYearCheck whether it is a leap year

2.2 Instant timestamp

The operation is performed with a description of the experience since the first year of Unix (traditionally January 1, 1970 as the UTC time zone)

  • Gets the timestamp of the current timetoEpochMilli
  • Gets the seconds of the current timegetEpochSecond
  • Offset the timeInstant.now().ofHours(ZoneOffset.ofHours(int hours))

2.3 TemporalAdjuster Time adjuster

TemporalAdjuster instance objects are mainly obtained through TemporalAdjusters tools

LocalDateTime now = LocalDateTime.now();
        // Call the JDK time corrector directly
        LocalDateTime with = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        System.out.println(with);
        // Define a time corrector to calculate the next working day
 LocalDateTime with2 = now.with(e -> {  LocalDateTime e1 = (LocalDateTime) e;  DayOfWeek dayOfWeek = e1.getDayOfWeek();  if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {  return e1.plusDays(3);  } else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {  return e1.plusDays(2);  } else {  return e1.plusDays(1);  }  });  System.out.println(with2); Copy the code

2.4 DateTimeFormatter Date Formatting

Three formatting methods:

  • Predefined standard formats
  • Locale-specific formats
  • Custom format

2.4.1 Predefined standard formats

The format provided by the JDK


LocalDate localDate = LocalDate.now();
String format = localDate.format(DateTimeFormatter.ISO_DATE);
Output: 2020-04-03
Copy the code

2.4.1 User-defined time format

// Customize the date formatting method. You can format dates using format and parse
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("Yyyy year MM month DD day");
String format1 = localDate.format(dateTimeFormatter);
System.out.println(format1);
localDate.parse(format1,dateTimeFormatter);
 Output: 2020years04month03day 2020-04-03 Copy the code

2.5 Time Zone Processing

2.5.1 ZoneId

  • Get all time zone information
 Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
Copy the code
  • Gets information about the specified time zoneZoneIdobject
ZoneId of = ZoneId.of("Asia/Chungking");
Copy the code

2.5.2 ZonedDateTime

Gets a datetime object with a time zone

ZonedDateTime now = ZonedDateTime.now();
        System.out.println(now);
/ / output
2020-04-03T14:22:54.250+08:00[Asia/Shanghai]
Copy the code

Other uses are the same as for the LocalDateTime class

This article is formatted using MDNICE