JDK 1.8 full date time Api (example attached at the end of the paper)

Background Before jdk 1.8, Java time use java . util.Date and java.util.Calendar classes. Date today = new Date(); Syste...
Background
2, JDK 1.8 new date time type
3, Time operation
4, Time date format
Five, summary

Background

Before jdk 1.8, Java time use java . util.Date and java.util.Calendar classes.

Date today = new Date(); System.out.println(today); // Convert to string SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String todayStr = sdf.format(today); System.out.println(todayStr);

Several questions about Date:

  1. If it is not formatted, the Date printed out by Date is not readable;
  2. SimpleDateFormat can be used to format time, but SimpleDateFormat is thread unsafe (static decoration SimpleDateFormat is disabled in Alibaba development manual);
  3. Date is troublesome to process time. For example, if you want to get the time of a year, a month, a week, or n days later, it's really too difficult to process it with date, and the getYear(), getMonth() methods of the date class are all discarded;

2, JDK 1.8 new date time type

Java 8 introduces a series of new API s that provide better support for time and date processing, and clearly defines some concepts of time and date, such as Instant, duration, date, time, time zone and Period.

  1. Local date: Date excluding time, such as 2019-10-14. It can be used to store birthdays, anniversaries, entry dates, etc.
  2. LocalTime: compared with LocalDate, it is the time without date.
  3. LocalDateTime: contains date and time, no offset information (time zone).
  4. Zonedatetime: contains the complete datetime of the time zone. The offset is based on UTC / Greenwich mean time.
  5. Instant: timestamp, similar to System.currentTimeMillis().
  6. Duration: indicates a time period.
  7. Period: used to measure a period of time in years and days.
  8. DateTimeFormatter: a new date resolution format class.

2.1 LocalDate

The LocalDate class contains only dates, not specific times. You can use it simply to represent a date and not a time.

public static void localDate() { //Get current date LocalDate today = LocalDate.now(); System.out.println("Current date:" + today); // Two ways to get the year int thisYear = today.getYear(); int thisYearAnother = today.get(ChronoField.YEAR); System.out.println("This year is" + thisYear + "year"); System.out.println("This year is" + thisYearAnother + "year"); // Acquisition month Month thisMonth = today.getMonth(); System.out.println(thisMonth.toString()); // This is the first few months of this year int monthOfYear = today.getMonthValue(); // int monthOfYear = today.get(ChronoField.MONTH_OF_YEAR); System.out.println("This month is the first of this year" + monthOfYear + "Months"); // Days of the month int length = today.lengthOfMonth(); System.out.println("This month" + length + "day"); // Two ways to get the day int thisDay = today.getDayOfMonth(); int thisDayAnother = today.get(ChronoField.DAY_OF_MONTH); System.out.println("Today is the first day of the month" + thisDay + "day"); System.out.println("Today is the first day of the month" + thisDayAnother + "day"); // Get week DayOfWeek thisDayOfWeek = today.getDayOfWeek(); System.out.println(thisDayOfWeek.toString()); // Today is the day of the week int dayOfWeek = today.get(ChronoField.DAY_OF_WEEK); System.out.println("Today is the first day of the week" + dayOfWeek + "day"); // Leap year or not boolean leapYear = today.isLeapYear(); System.out.println("This year is a leap year:" + leapYear); //Date of construction LocalDate anotherDay = LocalDate.of(2008, 8, 8); System.out.println("Date:" + anotherDay); }

2.2 LocalTime

LocalTime only gets time, not date. LocalTime is similar to LocalDate, except that LocalDate does not contain a specific time, while LocalTime does not contain a specific date.

public static void localTime() { // Get current time LocalTime nowTime = LocalTime.now(); System.out.println("Current time:" + nowTime); //Two ways to get hours int hour = nowTime.getHour(); int thisHour = nowTime.get(ChronoField.HOUR_OF_DAY); System.out.println("Current time:" + hour); System.out.println("Current time:" + thisHour); //Two ways to get points int minute = nowTime.getMinute(); int thisMinute = nowTime.get(ChronoField.MINUTE_OF_HOUR); System.out.println("Current points:" + minute); System.out.println("Current points:" + thisMinute); //Two ways to get seconds int second = nowTime.getSecond(); int thisSecond = nowTime.get(ChronoField.SECOND_OF_MINUTE); System.out.println("Current seconds:" + second); System.out.println("Current seconds:" + thisSecond); // Construct specified time (up to nanoseconds) LocalTime anotherTime = LocalTime.of(20, 8, 8); System.out.println("Construction specified time:" + anotherTime); }

2.3 LocalDateTime

LocalDateTime represents a combination of date and time. You can create it directly through the of() method, or call the atTime() method of LocalDate or the atDate() method of LocalTime to merge the LocalDate or LocalTime into a LocalDateTime.

public static void localDateTime() { // Current date and time LocalDateTime today = LocalDateTime.now(); System.out.println("Now is:" + today); // Create the specified date and time LocalDateTime anotherDay = LocalDateTime.of(2008, Month.AUGUST, 8, 8, 8, 8); System.out.println("The specified time for creation is:" + anotherDay); // Splicing date and time // Use the current date to specify the LocalDateTime generated by the time LocalDateTime thisTime = LocalTime.now().atDate(LocalDate.of(2008, 8, 8)); System.out.println("The date of splicing is:" + thisTime); // Use the current date to specify the LocalDateTime generated by the time LocalDateTime thisDay = LocalDate.now().atTime(LocalTime.of(12, 24, 12)); System.out.println("The date of splicing is:" + thisDay); // Specify date and time to generate LocalDateTime LocalDateTime thisDayAndTime = LocalDateTime.of(LocalDate.of(2008, 8, 8), LocalTime.of(12, 24, 12)); System.out.println("The date of splicing is:" + thisDayAndTime); // Get LocalDate LocalDate todayDate = today.toLocalDate(); System.out.println("Today's date is:" + todayDate); // Get LocalTime LocalTime todayTime = today.toLocalTime(); System.out.println("Now the time is:" + todayTime); }

2.4 Instant

Instant is used to get a timestamp, similar to System.currentTimeMillis(), but instant can be accurate to nanoseconds.

public class InstantDemo { public static void main(String[] args) { // Create an Instant object Instant instant = Instant.now(); // Created by the ofEpochSecond method (the first parameter represents seconds and the second parameter represents nanoseconds) Instant another = Instant.ofEpochSecond(365 * 24 * 60, 100); // Get seconds long currentSecond = instant.getEpochSecond(); System.out.println("Get seconds:" + currentSecond); // Get milliseconds long currentMilli = instant.toEpochMilli(); System.out.println("Get milliseconds:" + currentMilli); } }

2.5 Duration

The internal implementation of Duration is similar to that of Instant, but Duration represents the time period, which can be created through the between method or the of() method.

public static void duration() { LocalDateTime from = LocalDateTime.now(); LocalDateTime to = LocalDateTime.now().plusDays(1); // Created through the between() method Duration duration = Duration.between(from, to); // Created with the of() method, which takes the length of the time period and the time unit. // 7 days Duration duration1 = Duration.of(7, ChronoUnit.DAYS); // 60 seconds Duration duration2 = Duration.of(60, ChronoUnit.SECONDS); }

2.5 Period

Period is similar to Duration. You can get a time period, but the unit is mm / DD / yyyy. You can also create it through the of method and the between method. The parameter received by the between method is LocalDate.

private static void period() { // By of method Period period = Period.of(2012, 12, 24); // Through the between method Period period1 = Period.between(LocalDate.now(), LocalDate.of(2020,12,31)); }

3, Time operation

3.1 time comparison

isBefore() and isAfter() determine whether a given time or date is before or after another time / date.
Take LocalDate for example. LocalDateTime/LocalTime are the same.

public static void compare() { LocalDate thisDay = LocalDate.of(2008, 8, 8); LocalDate otherDay = LocalDate.of(2018, 8, 8); // Later than boolean isAfter = thisDay.isAfter(otherDay); System.out.println(isAfter); // Earlier than boolean isBefore = thisDay.isBefore(otherDay); System.out.println(isBefore); }

3.2 increase / decrease the number of juveniles, months and days

Take LocalDateTime for example. LocalDate/LocalTime is the same.

public static void plusAndMinus() { // increase LocalDateTime today = LocalDateTime.now(); LocalDateTime nextYearDay = today.plusYears(1); System.out.println("The next year is today:" + nextYearDay); LocalDateTime nextMonthDay = today.plus(1, ChronoUnit.MONTHS); System.out.println("Today next month is:" + nextMonthDay); //reduce LocalDateTime lastMonthDay = today.minusMonths(1); LocalDateTime lastYearDay = today.minus(1, ChronoUnit.YEARS); System.out.println("A month ago:" + lastMonthDay); System.out.println("A year ago:" + lastYearDay); }

3.3 time modification

Modify time with

public static void edit() { LocalDateTime today = LocalDateTime.now(); // Change year to 2012 LocalDateTime thisYearDay = today.withYear(2012); System.out.println("The modified time is:" + thisYearDay); // Revised to December LocalDateTime thisMonthDay = today.with(ChronoField.MONTH_OF_YEAR, 12); System.out.println("The modified time is:" + thisMonthDay); }

3.4 time calculation

Time is calculated by the static method and Duration of TemporalAdjusters

public static void compute() { // The static method of TemporalAdjusters LocalDate today = LocalDate.now(); // Get the first day of the year LocalDate date = today.with(firstDayOfYear()); System.out.println("The first day of the year is:" + date); // Duration calculation LocalDateTime from = LocalDateTime.now(); LocalDateTime to = LocalDateTime.now().plusMonths(1); Duration duration = Duration.between(from, to); // Interval statistical conversion // Total days long days = duration.toDays(); System.out.println("Be apart" + days + "day"); // Hours long hours = duration.toHours(); System.out.println("Be apart" + hours + "hour"); // Minute number long minutes = duration.toMinutes(); System.out.println("Be apart" + minutes + "Minute"); }
  • More ways to TemporalAdjusters
Method name describe dayOfWeekInMonth() Return to the day of the week in the same month firstDayOfMonth() Return to the first day of the month firstDayOfNextMonth() Back to the first day of next month firstDayOfNextYear() Back to the first day of the next year firstDayOfYear() Return to the first day of the year firstInMonth() Return to the day of the first week of the same month lastDayOfMonth() Return to the last day of the month lastDayOfNextMonth() Back to the last day of next month lastDayOfNextYear() Return to the last day of the next year lastDayOfYear() Return to the last day of the year lastInMonth() Return to the last day of the same month next() / previous() Day of week given after / before return nextOrSame() / previousOrSame() Returns the given day of the next / previous week. If this value meets the condition, it will be returned directly

4, Time date format

4.1 format time

DateTimeFormatter provides multiple formatting methods by default. If the default cannot meet the requirements, you can create a custom formatting method by using the ofPattern method of DateTimeFormatter.

public static void format() { LocalDate today = LocalDate.now(); // Two default format time modes String todayStr1 = today.format(DateTimeFormatter.BASIC_ISO_DATE); String todayStr2 = today.format(DateTimeFormatter.ISO_LOCAL_DATE); System.out.println("Format time:" + todayStr1); System.out.println("Format time:" + todayStr2); //Custom formatting DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String todayStr3 = today.format(dateTimeFormatter); System.out.println("Custom format time:" + todayStr3); }

4.2 analysis time

In 4.1, we need to parse the format in the same way.

public static void parse() { LocalDate date1 = LocalDate.parse("20080808", DateTimeFormatter.BASIC_ISO_DATE); LocalDate date2 = LocalDate.parse("2008-08-08", DateTimeFormatter.ISO_LOCAL_DATE); System.out.println(date1); System.out.println(date2); }

Five, summary

Advantages over Date

  1. Instant has higher accuracy, which can be accurate to nanosecond level;
  2. Duration can easily get the days, hours, etc. in the time period;
  3. LocalDateTime can quickly get the year, month, day, next month, etc;
  4. TemporalAdjusters class contains many common static methods to avoid writing their own tool classes;
  5. Compared with Date's format SimpleDateFormat, DateTimeFormatter is thread safe.

5.1 example code

Github sample code

5.2 technical exchange

  1. Eolian blog
  2. Dust blog - gold digger
  3. FengChen blog blog Garden
  4. Github
HuaZi_Myth 168 original articles published, 3 praised, 7699 visited Private letter follow

6 February 2020, 03:38 | Views: 7724

Add new comment

For adding a comment, please log in
or create account

0 comments