java8 processing date and time

Java 8 How to handle dates and times

1. Get today's date in Java 8

  • Java LocalDate 8 is used to represent today's date. And java.util.Date different, it dates only, does not include the time. When you only need to use this class represents the date.
LocalDate now = LocalDate.now();
System.out.println(now);

//结果
2018-06-20

2. Obtain the year, month, date information in Java 8

  • LocalDate class provides get in, quick way to month, day, and it also contains many other examples of the date attribute. By calling these methods can easily get the required date information, not like before, we need to rely on a class java.util.Calendar
LocalDate now = LocalDate.now();
int year = now.getYear();
int monthValue = now.getMonthValue();
int dayOfMonth = now.getDayOfMonth();
System.out.printf("year = %d, month = %d, day = %d", year, monthValue, ayOfMonth);

//结果
year = 2018, month = 6, day = 20

3. handle specific date in Java 8 in

  • In the first example, we through the static factory method now () is very easy to create today's date, you can also call another useful factory methods LocalDate.of () to create any date, this method requires passing year, month , Japan as an argument and returns the corresponding instance LocalDate. The advantage of this approach is that design errors did not repeat the old API, such as the year starting in 1900, the month is zero, and so on. WYSIWYG date, as the following example shows the June 20, no hidden organ.
LocalDate date = LocalDate.of(2018, 06, 20);
System.out.println(date);

4. In Java 8 is determined whether the same two dates

  • Analyzing two dates are equal
LocalDate now = LocalDate.now();
LocalDate date = LocalDate.of(2018, 06, 20);
if (date.equals(now)) {
    System.out.println("同一天");
}

5. Check this recurring events like birthdays in Java 8 in

  • Java how to check these festivals or other periodic events it? The answer is MonthDay class. This class combines month and day, remove the years, which means you can use it to determine the occurrence of events every year. This class is similar and there is a YearMonth class. These classes are also immutable and thread-safe value type.

LocalDate now = LocalDate.now();
LocalDate dateOfBirth = LocalDate.of(2018, 06, 20);
MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(now);
if (currentMonthDay.equals(birthday)) {
    System.out.println("Happy Birthday");
} else {
    System.out.println("Sorry, today is not your birthday");
}

//结果
Happy Birthday

6. Get the current time in Java 8

  • Examples of the date of acquisition and Java 8 like, acquisition time using LocalTime class, a time not only LocalDate date of next of kin. You can call a static factory method now () to get the current time. The default format is hh: mm: ss: nnn.
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
//结果可以看到当前时间就只包含时间信息,没有日期。
13:35:56.155

7. How to add existing time in hours

  • Java 8 in addition to the same types of benefits and thread-safe, but also provides better plusHours () method replaces add (), and are compatible. Note that these methods return a new instance of LocalTime, because of its inflexibility, the return must use variable assignment.
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
LocalTime localTime1 = localTime.plusHours(2);//增加2小时
System.out.println(localTime1);

//结果
13:41:20.721
15:41:20.721

8. How to calculate the date a week later

  • LocalDate date does not contain time information, it is plus () method is used to increase the days, weeks, months, ChronoUnit class declares these units of time. Since LocalDate is the same type, the return must use variable assignment.
LocalDate now = LocalDate.now();
LocalDate plusDate = now.plus(1, ChronoUnit.WEEKS);
System.out.println(now);
System.out.println(plusDate);
//结果
2018-06-20
2018-06-27

9. Calculate the date after a year or a year ago

  • Using a minus () method of calculating a historical date
LocalDate now = LocalDate.now();
LocalDate minusDate = now.minus(1, ChronoUnit.YEARS);
LocalDate plusDate1 = now.plus(1, ChronoUnit.YEARS);
System.out.println(minusDate);
System.out.println(plusDate1);

//结果
2017-06-20
2019-06-20

10. Use Java Clock CLOCK 8

  • Java 8 adds a Clock class used to obtain the time clock timestamp, or the current date and time in the time zone information. Where previously used System.currentTimeInMillis () and TimeZone.getDefault () are available Clock replacement.

Clock clock = Clock.systemUTC();
Clock clock1 = Clock.systemDefaultZone();
System.out.println(clock);
System.out.println(clock1);

//结果
SystemClock[Z]
SystemClock[Asia/Shanghai]

11. How to judge Java date is before or after another date in

  • In Java 8, LocalDate class has two methods isBefore () and isAfter () for the date comparison. When calling isBefore () method, if the current date is less than the given date it returns true.
LocalDate tomorrow = LocalDate.of(2018,6,20);
 if(tomorrow.isAfter(now)){
     System.out.println("Tomorrow comes after today");
 }
 LocalDate yesterday = now.minus(1, ChronoUnit.DAYS);
 if(yesterday.isBefore(now)){
     System.out.println("Yesterday is day before today");
 }

Region 12. When the processing in Java 8

  • Java 8 is not only separate the date and time, and also to separate out the time zone. There are a series of individual hydrocarbons such as ZoneId to handle a particular time zone, ZoneDateTime classes to represent the time at a certain time zone. It had previously been in Java 8 GregorianCalendar class to do.
ZoneId america = ZoneId.of("America/New_York");
LocalDateTime localtDateAndTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInNewYork  = ZonedDateTime.of(localtDateAndTime, america );
System.out.println(dateAndTimeInNewYork);

13. how to represent this type of credit card expiration date is fixed, the answer lies in YearMonth

  • Check for duplicate events with similar MonthDay example, YearMonth is another combination class for representing a credit card expiration date, FD maturity, futures options expiration dates. You can also use this class to get the total number of days of the month, YearMonth instance lengthOfMonth () method returns the number of days of the month, in the judgment of February has 28 days, or 29 days is very useful.
 YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
YearMonth creditCardExpiry = YearMonth.of(2018, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);

//结果
Days in month year 2018-06: 30
Your credit card expires on 2018-02

14. How to check the leap year in Java 8

  • LocalDate class has a very practical method isLeapYear () This example determines whether it is a leap year.

15. The computing the number of days between two dates and the month

  • There is a common operation date is calculated the number of days between two dates, weeks, or months. Java 8 can be done in the calculation java.time.Period class. The following example, we calculate the number of months between the day and the future one day.
 LocalDate date = LocalDate.of(2019, Month.MARCH, 20);
Period period = Period.between(now, date);
System.out.println("离下个时间还有" + period.getMonths() + " 个月");

16. The difference includes the date and time information

  • In the Java 8, ZoneOffset class is used to represent the time zone, for example, a difference of +05 region of India GMT or UTC standard: 30, can be acquired by the time zone corresponding ZoneOffset.of () static method. Once you get the time difference can be created by passing a OffSetDateTime objects LocalDateTime and ZoneOffset.

    
    LocalDateTime datetime = LocalDateTime.of(2014, Month.JANUARY, 14,19,30);
    ZoneOffset offset = ZoneOffset.of("+05:30");
    OffsetDateTime date = OffsetDateTime.of(datetime, offset);  
    System.out.println("Date and Time with timezone offset in Java : " + date);

17. Get the current timestamp in Java 8

  • If you remember how Java 8 is obtained before the current timestamp, so now you finally freed. Instant class has a static factory method now () returns the current timestamp
  • In the same time stamp information includes the date and time, and java.util.Date like this. Instant class does in fact identical to the previous Java Date class 8, you can use the Date class and a respective class Instant mutual conversion method of converting, for example: Date.from (Instant) is converted to the Instant java.util.Date, Date.toInstant () is converted into Instant sucked Date class category.
 Instant timestamp = Instant.now();
System.out.println(timestamp);
//  结果
2018-06-20T06:35:24.881Z

18. How to use predefined formatting tools in Java 8 to parse or format dates

  • 8 in the world before Java, the date and time format is very strange, the only help class SimpleDateFormat is not thread-safe, but also as a local variable is cumbersome when parsing and formatting dates. Fortunately, thread-local variables make it becomes available in a multithreaded environment, but this is the past. Java 8 introduces a new date and time formatting tools, thread-safe and easy to use. It comes with a number of commonly used built-in formatting tools.

19. how to use custom date formatting tools resolved in Java

  • Despite the built-in formatting tools useful, sometimes you need to define a specific date format. We can call the DateTimeFormatter ofPattern () static method and pass in any format to return to their example, and format characters as before on behalf of, M for monthly, m sub-delegation. If the format is not standardized DateTimeParseException will throw an exception, but only if the written m M This logic error will not throw the exception.
 //DateTimeFormatter 如何使用:

//解析日期
String dateStr= "2018年06月20日";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");   
LocalDate date= LocalDate.parse(dateStr, formatter);

//日期转换为字符串

LocalDateTime now = LocalDateTime.now();  
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm a");
String nowStr = now .format(format);

20. How to convert the string to date Java 8

  • Examples LocalDateTime date converting a string of a specific format. This is by far the most Java Date to String a simple way. The following example will return a formatted string for the day. And like before, still you need to create DateTimeFormatter instance and incoming format, but it is back to the calling format () method, rather than parse () method. This method will be converted into a string of incoming date specified format.
LocalDateTime arrivalDate  = LocalDateTime.now();
try {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMMdd yyyy  hh:mm a");
    String landing = arrivalDate.format(format);
    System.out.printf("Arriving at :  %s %n", landing);
}catch (DateTimeException ex) {
    System.out.printf("%s can't be formatted!%n", arrivalDate);
    ex.printStackTrace();
}

Guess you like

Origin blog.51cto.com/yushiwh/2429062