Introduction to the new feature time class of java8

        java8 has been out for a long time, and java9 will be out soon. To be honest, some features in java8 are rarely used, which may be related to the speed of updating their knowledge, because the project needs to use the newly introduced time in java8 class, so here I mainly refer to other people's articles and my own use to summarize, and also keep it for myself in the future.

        refer to

        http://blog.csdn.net/chenleixing/article/details/44408875

        http://www.cnblogs.com/565261641-fzh/p/5683594.html

        http://blog.csdn.net/jingyuwang1/article/details/72858695

        jdk1.8 introduced new date and time components and grouped them under a series of packages. Why develop a whole new API for dealing with dates and times? Because the old java.util.Date is very hard to use. For example, the month of java.util.Date starts from 0, January is 0, and December is 11, so you have to manually calculate it when you use it. However, in the jdk1.8 version, the month and week of java.time.LocalDate have been changed to enum, and the enumeration value can be called directly when using it, and there will be no error. At the same time, the calendar used in the core package java.time adopts the ISO-8601 standard. Of course, we can also use some non-standard calendars in the java.time.chrono package, such as the Japanese imperial calendar (the emperor’s year number), the Thai Buddhist calendar ( The birth of Buddha), the Republic of China calendar (the Revolution of 1911), the Islamic Black Chilla calendar.

The new date and time related classes in jdk1.8 are thread-safe, why are they thread-safe? It is because they are all decorated with final, so once all the date and time values ​​are initialized, they will not change, and the ava.util.Date defined in the version before jdk1.8 is defined as modifiable and implements SimpleDateFormat become non-thread safe. java.util.Date is a "universal interface" that contains date, time, and milliseconds. If you only want to use java.util.Date to store dates, or only time, then only you know which parts of the data are useful and which parts of the data are not available. In the new Java 8, date and time are clearly divided into LocalDate and LocalTime, LocalDate cannot contain time and LocalTime cannot contain date. Of course, LocalDateTime can contain both date and time. The new time and date API in jdk1.8 is located in the java.time package. Here are some key classes in it:

       .Instant - Essentially a digital timestamp, the bottom layer is actually a wrapper around System.currentTimeMillis().

       .LocalDate - a date without a specific time, such as 2014-01-14. It can be used to store birthdays, anniversaries, entry dates, etc.

       .LocalTime - It represents the time without date in the format 13:01:02.221.

       .LocalDateTime - It contains the date and time, but still no offset information or time zone.

       .Period - the difference in days, months, and years between two dates. Of course, we can also use the until method in the date directly to achieve the same effect.

       .Duration - seconds and nanoseconds between two datetimes.

       .ZonedDateTime - This is a full datetime including the timezone and the offset is based on UTC/Greenwich.

Of course, the DateTimeFormatter class for date formatting has been added in jdk1.8. In the following example, the operation of the new date-related class will be introduced, which basically includes the requirements for daily use. If you need more detailed related classes Use the method to view the specific jdk1.8 related API.

       1. Get the current date

//get current date
LocalDate today = LocalDate.now();
System.out.println(today);

       2. Get the current year, month and day

//Get the current year, month and day
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.printf("The current year, month and day are: year=%d, month=%d, day=%d \t %n",year,month,day);

        3. Create a specific date

// create a specific date
LocalDate birthDay = LocalDate.of(2013,9,5);
System.out.println("Create a specific date:" + birthDay.toString());

        4. Compare 2 dates for equality

// Compare 2 dates for equality
//LocalDate localDate1 = LocalDate.of(2017,10,27);
LocalDate localDate1 = LocalDate.of(2013,9,5);
LocalDate today = LocalDate.now();
if(localDate1.equals(today)){
    System.out.printf("today %s and localDate1 %s are same date \t %n", today, localDate1);
}else {
    System.out.printf("today %s and localDate1 %s are not same date \t %n", today, localDate1);
}

         5. Check for recurring events like birthdays

// Check if it is a repeating event like birthday
LocalDate birthDay = LocalDate.of(2013,10,27);
MonthDay monthDay = MonthDay.of(birthDay.getMonthValue(),birthDay.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.now();
if(monthDay.equals(currentMonthDay)){
    System.out.println("happy birthday");
}else {
    System.out.println("Sorry,today is not your birthday");
}

            6. Get the current time

//get current time
LocalTime currentTime = LocalTime.now();
System.out.println("Current time: " + currentTime);

             7. Add hours to the current time

//Add hours, minutes and seconds to the current time to call different functions, and subtract the time to call different functions
LocalTime currentTime = LocalTime.now();
int plusHours = 2;
currentTime = currentTime.plusHours(plusHours);
System.out.println("The time after adding " + plusHours + " to the current time is: " + currentTime);

           8. Get the date a week later

//Get the date one week later, get other related dates and call different parameters or functions
LocalDate today = LocalDate.now();
LocalDate nextWeekDay = today.plus(1, ChronoUnit.WEEKS);
System.out.println("One week later today is: " + nextWeekDay);

            9. Obtain the current instantaneous time, date or time in a certain time zone according to Clock

//Get the current instantaneous time, date or time in a time zone, which can replace the System.currentTimeInMillis() and TimeZone.getDefault() methods
Clock clock = Clock.systemUTC();
System.out.println(clock.instant().toString());
System.out.println("Current time in milliseconds from 1970-01-01T00:00Z (UTC):" + clock.millis());
Clock clock1 = Clock.systemDefaultZone();
System.out.println(clock1.instant().toString());

             10. Sequence of test dates

//The order of the test dates
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minus(1,ChronoUnit.DAYS);
if(yesterday.isBefore(today)){
    System.out.println(yesterday + "比" + today + "早");
}else {
    System.out.println(yesterday + "比" + today + "晚");
}

            11. Handling different time zones

// handle different time zones
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime,ZoneId.of("America/New_York"));
System.out.println(zonedDateTime.toString());

            12. Test the number of days in a month

//Test the number of days in a month
YearMonth yearMonth = YearMonth.now();
int days = yearMonth.lengthOfMonth();
System.out.printf("The current year is: %d, the month is: %d, a total of: %d days\n",yearMonth.getYear(),yearMonth.getMonthValue(),days);

            13. Test for leap year

//Test for leap year
//LocalDate today = LocalDate.now();
LocalDate today = LocalDate.of(2016,5,6);
if(today.isLeapYear()){
    System.out.printf("The current year is %d and is a leap year\n", today.getYear());
}else {
    System.out.printf("The current year is %d, and it is a normal year\n", today.getYear());
}

            14. Test the number of days and months between 2 dates, the number of years

//Test the number of days and months between 2 dates, the number of years
LocalDate today = LocalDate.now();
LocalDate localDate = LocalDate.of(2016,3,29);
Period period = Period.between(localDate,today);
System.out.printf("The time interval between %s and %s is %d years %d months %d days\n",today,localDate,period.getYears(),period.getMonths(),period. getDays());
/ / Calculate the date interval directly using the method in the date class
long days = localDate.until(today,ChronoUnit.DAYS);
System.out.println("Use the date class to calculate the number of days between: " + days);
long weeks = localDate.until(today,ChronoUnit.WEEKS);
System.out.println("Use the date class to calculate the number of weeks between intervals:" + weeks);

            15. Test seconds and nanoseconds for 2 time direct intervals

//Test seconds and nanoseconds between 2 times directly separated
LocalDateTime now = LocalDateTime.now();
LocalDateTime yesterdayNow = now.minusDays(1).minusNanos(2);
Duration duration = Duration.between(yesterdayNow,now);
System.out.printf("%d seconds %d nanoseconds between %s and %s\n",yesterdayNow,now,duration.get(ChronoUnit.SECONDS),duration.get(ChronoUnit.NANOS));

            16. Date and time with time zone offset

//date and time with timezone offset
LocalDateTime localDateTime = LocalDateTime.of(2017,6,8,12,20,30);
//Add India's time zone GMT or UTC 5:30
ZoneOffset zoneOffset = ZoneOffset.of("+05:30");
OffsetDateTime offsetDateTime = OffsetDateTime.of(localDateTime,zoneOffset);
System.out.println("Date and time with time zone offset: "+ offsetDateTime.toString());

            17. Get the current timestamp

//get current timestamp
Instant instant = Instant.now();
System.out.println("The current timestamp is: " + instant);

            18. Test formatting time

//Test format time
String date = "20171027";
LocalDate formatDate = LocalDate.parse(date, DateTimeFormatter.BASIC_ISO_DATE);
System.out.printf("Date %s before formatting, date %s after formatting\n", date, formatDate);

            19. Custom Formatting

//Customize the format, the custom format should be the same as the formatted string representation, otherwise an error will be reported
String date = "2017 1027";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy MMdd");
LocalDate formatDate = LocalDate.parse(date, dateTimeFormatter);
System.out.printf("Date %s before custom formatting, date %s after formatting\n", date, formatDate);

             20. Date formatted as string

//The date is formatted as a string, which can be customized
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy MM dd hh:ss:mm");
String formatDateTime = dateTimeFormatter.format(now);
System.out.println("Format date as string: " + formatDateTime);

             21. Get current time in milliseconds, microseconds, nanoseconds and convert from milliseconds to time

//Get current time in milliseconds, microseconds, nanoseconds and convert from milliseconds to time
Instant instant = Instant.now();
System.out.println("Current time:" + instant.toString());
//millisecond
System.out.println("Current time in milliseconds:" + instant.get(ChronoField.MILLI_OF_SECOND));
// microseconds
System.out.println("The current time in microseconds:" + instant.get(ChronoField.MICRO_OF_SECOND));
//nanoseconds
System.out.println("The current time in nanoseconds:" + instant.get(ChronoField.MICRO_OF_SECOND));
//Millisecond to Instant
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println("Milliseconds to Instant:" + localDateTime);

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326692569&siteId=291194637