Traditional time API
The Date class
-
The Date class has been in the standard library since Java was first introduced, but all of its methods have been deprecated since Java 1.1
-
Use the sample
// Get the current time, toString: Wed Jan 01 00:00:00 CST 2020 Date date = new Date(); // The corresponding timestamp, of type long long stamp = d.getTime(); Copy the code
The Calendar class
-
Java 1.1 recommends using the Calendar class to handle time
-
Use the sample
// Get Calendar instance, default current time Calendar calendar = Calendar.getInstance(); // Set the time of the Calendar object with setTime() calendar.setTime(new Date()); // Get the corresponding Date object with getTime() Date date = calendar.getTime(); // Set the time by year, month, day, hour, minute, and second. Month starts from 0 calendar.set(2020.1.1); calendar.set(2020.1.1.8.30.30); // Set (int field, int value calendar.set(Calendar.MONTH, 0); // Use get(int field) to get the corresponding time field int month = calendar.get(Calendar.MONTH) + 1; // Use the after and before methods to compare the order of Calendar objects and return a Boolean value Calendar oldCalendar = Calendar.getInstance(); oldCalendar.set(2019.1.1.8.30.30); boolean after = calendar.after(oldCalendar); Copy the code
Existing problems
-
Time difficulty
The direct conversion between ms value and date is tedious, and there are many steps to calculate the time difference by ms value
-
Thread safety
The SimpleDateFormat class is thread-unsafe, and globally sharing a Calendar object in the SimpleDateFormat class can be an exception in the case of multiple threads
Because the Format method of the SimpleDateFormat class executes with an error time reported by a Calendar type member variable, the problem arises when the variable is shared by multiple threads
Java8 new time API
Time package common classes
-
Instant class
The Instant class models a single instantaneous point on the timeline and can be used to record event timestamps in the application. It can be used as an intermediate class to complete the conversion in the subsequent type conversion
-
Duration class
The Duration class represents seconds or nanosecond intervals and is suitable for dealing with shorter times that require greater precision
-
Period which
The Period class represents the year, month, or day of a Period of time
-
LocalDate class
LocalDate is an immutable date-time object that represents a date, usually regarded as year-month-day
-
LocalTime class
LocalTime is an immutable date-time object that represents a time, usually thought of as hour-second, with time represented as nanosecond precision
-
LocalDateTime class
The LocalDateTime class is an immutable datetime object that represents datetime and is usually treated as year-month-day-hour-minute-second
-
ZonedDateTime class
ZonedDateTime is an immutable representation of a datetime with a time zone. This class stores all date and time fields with an accuracy of nanosecond, and the time zone is the region offset, for handling fuzzy local date and time
A now method
-
The now method creates an instance based on the current date or time
-
Use the sample
// Create an instance object of Instant using the now method Instant instantNow = Instant.now(); // Use the now method to create an instance object of LocalDate LocalDate localDateNow = LocalDate.now(); // Use the now method to create an instance object of LocalTime LocalTime localTimeNow = LocalTime.now(); // Create an instance object of LocalDateTime using the now method LocalDateTime localDateTimeNow = LocalDateTime.now(); // Create an instance of ZonedDateTime using the now method ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(); Zulu time (GMT/UTC) System.out.println("Instant:" + instantNow); // YY-MM-DD System.out.println("LocalDate:" + localDateNow); // Time: minute: second HH:mm:ss System.out.println("LocalTime:" + localTimeNow); // year - month - day T: minute: second System.out.println("LocalDateTime:" + localDateTimeNow); // year-month-day T hour: minute: second +08:00[Asia/Shanghai] indicates the time zone System.out.println("ZonedDateTime:" + zonedDateTimeNow); /* Instant: 2020-11-26T08:12:23.426z LocalDate: 2020-11-26T16:12:23.473 LocalDate: 2020-11-26T16:12:23.473 ZonedDateTime: the T16 2020-11-26: ". 473 + 08:00 Asia/Shanghai * / Copy the code
-
Other classes in the time package can also use the NOW method to get more precise information
-
Year class (Year)
-
YearMonth class (year)
-
Class MonthDay (month and day)
-
Method of
-
The of method generates a date/time object based on the given argument
-
Use the sample
// 8 August 2018 LocalDate localDate = LocalDate.of(2018.8.8); // 8 minutes 8 seconds, the second is 0 or omitted toString is not displayed LocalTime localTime = LocalTime.of(8.8.8); // August 8, 2018, 8:08 minutes and 8 seconds LocalDateTime localDateTime = LocalDateTime.of(2018.8.8.8.8.8); System.out.println("localTime: " + localTime); System.out.println("localDate: " + localDate); System.out.println("localDateTime:" + localDateTime); /* localDate: 2018-08-08 localTime: 08:08:08 localDate: 2018-08-08T08:08:08 */ Copy the code
ZoneId time class
-
ZoneId Indicates the time zone
-
ZoneId getAvailableZoneIds returns a set, contains about 600 time zones, such as Asia/Shanghai
-
Zoneid. of returns the time zone object in a string representing the time zone
-
ZonedDateTime Sets the time zone
/ / get LocalDateTime LocalDateTime localDate = LocalDateTime.now(); // LocalDateTime atZone returns ZonedDateTime object // Set the LocalDateTime object to Shanghai ZonedDateTime zonedDateTime = localDate.atZone(ZoneId.of("Asia/Shanghai")); System.out.println(zonedDateTime); // Get the corresponding time zone in Tokyo ZonedDateTime tokyoDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo")); System.out.println(tokyoDateTime); / * the T16 2020-11-26:54:31. 692 + 08:00 Asia/Shanghai T17:2020-11-26 54:31. 692 + 09:00 Asia/Tokyo * / Copy the code
The Month enumeration class
-
Month Month enumeration
// Use the Month enumeration to get the Month LocalDateTime localDate = LocalDateTime.of(2018, Month.AUGUST, 8.8.8); Copy the code
Note that old Calendar months start at 0 and LocalDate/LocalDateTime months start at 1
-
The Month of method
Month month = Month.of(12); System.out.println(month); // DECEMBER Copy the code
Plus,minusmethods
-
LocalDate plus method
- LocalDate plusDay(Long days) Specifies the number of days added
- LocalDate plusWeeks(long weeks) Adds the number of weeks
- LocallDate plusMonths(Long months) Indicates the months added
- LocalDate plusYears(Long years) Adds the number of years
-
The plus method of LocalTime
- LocalTime plusNanos(Long Nanos) added nanoseconds
- LocalTime plusSeconds(long seconds) Adds seconds
- LocalTime plusMinutes(Long minutes) Add minutes
- LocalTime plusHours(Long hours) Adds hours
-
plus(TemporalAmount amoutToadd)
TemporalAmount is an interface, and Period is its implementation class, representing a Period of time
LocalDateTime localDateTime = LocalDateTime.now(); // 1 year, 2 months and 3 days Period p = Period.of(1.2.3); // Add p to localDateTime LocalDateTime dateTimeAfterPlus = localDateTime.plus(p); Copy the code
-
plus(long amountToadd, TemporalUnit unit)
TemporalUnit is an interface, and ChronoUnit is its implementation class, encapsulating many time periods
LocalDateTime localDateTime = LocalDateTime.now();// Add 1 day localDateTime1 = localDatetime. plus(1, chronounit.days); // Add 2 HOURS localDateTime2 = localDatetime. plus(2, chronounit.hours); Copy the code
With the method
-
The with method allows you to modify a time item directly
- LocalDateTime withNano(int I) Changes to nanoseconds
- LocalDateTime withSecond(int I) Change seconds
- LocalDateTime withMinute(int I) Changes the branch
- LocalDateTime withHour(int I) Change hour
- LocalDateTime withDayOfMonth(int I) Change day
- LocalDateTime withMonth(int I) Change month
- LocalDateTime withYear(int I) Change year
-
with(TemporalField field, long newValue)
TemporalField is an interface and ChronoField is its implementation class, providing an enumeration of many date fields
LocalDateTime localDateTime = LocalDateTime.of(2018.8.8.8.8.8);LocalDateTime localDateTimeModified = LocalDateTime. withMonth(10); LocalDateTime localDateTimeModified = localDatetime. with(chronofield.month_of_year, 10); Copy the code
-
with(TemporalAdjuster adjuster)
TemporalAdjuster is a functional interface that allows you to customize the TemporalAdjuster implementation class for desired modifications
TemporalAdjusters encapsulates many methods that return to the realization of TemporalAdjuster
The Next and Previous methods of TemporalAdjusters, combined with the DayOfWeek enumeration class, enable easy access to the next week or the day of the week
LocalDateTime localDateTime = LocalDateTime.of(2018.8.8.8.8.8);/ / to the first day of the month LocalDateTime localDateTime1 = LocalDateTime. With (TemporalAdjusters. FirstDayOfMonth ()); / / to the first day of next month LocalDateTime localDateTime2 = LocalDateTime. With (TemporalAdjusters. FirstDayOfNextMonth ()); // Customize TemporalAdjuster, LocalDateTime3 = LocalDateTime. with(new TemporalAdjuster() {@override public Temporal adjustInto(Temporal temporal) { return temporal.with(ChronoField.DAY_OF_MONTH, temporal.range(ChronoField.DAY_OF_MONTH).getMaximum() -1 ); }}); // Next and previous methods work with the DayOfWeek enumeration class, for example: Next FRIDAY LocalDateTime localDateTime4 = LocalDateTime. with(TemporalAdjusters. Next (dayofweek.Friday)); Copy the code
The query method
-
LocalDate and LocalTime have a query method to query dates
-
R Query (TemporalQuery Query) is a generic method that returns data of the type of the passed generic class
-
TemporalQuery is a generic interface that overrides its queryFrom(TemporalAccessor temporal) method to return data in passing time
LocalDate localDate = LocalDate.of(2018.8.8);Boolean isAfterLabour = localdate.query (new TemporalQuery
() {@override public Boolean queryFrom(TemporalAccessor temporal) { LocalDate today = LocalDate.from(temporal); LocalDate labour = LocalDate.of(today.getYear(), 5 ,1); return today.isAfter(labour); }}); Copy the code
The parse and format
-
The parse method is a static method of LocalDate and LocalDateTime that converts a string to a time or date object
-
Format is an instance method of LocalDate and LocalDateTime, used to format strings
-
The DateTimeFormatter class encapsulates the commonly used format as a static variable, or you can customize the format using the ofPattern method
Parse ("2018-08-08"); // localdate. parse("2018-08-08"); // localdate. parse("2018-08-08"); / / LocalDate. Parse the specified format LocalDate parsedDate2 = LocalDate. Parse (" 2018/11/1 ", DateTimeFormatter ofPattern (" yyyy/M/d ")); LocalDateTime LocalDateTime = LocalDateTime. Of,8,8,8,8,8 (2018); 2018-08-08String s1 = localDateTime.format(datetimeformatter.iso_date); 2018-08-08String s1 = localDateTime. // 2018-08-08T08:08:08String s2 = localDateTime.format(DateTimeFormatter.ISO_DATE_TIME); / / DateTimeFormatter ofPattern custom format - > 2018.08.08 String s3 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy.MM.dd")); Copy the code