Home > Java > javaTutorial > Detailed example of the date API, a new feature in Java 8

Detailed example of the date API, a new feature in Java 8

黄舟
Release: 2017-07-22 15:50:01
Original
1518 people have browsed it

Java 8 includes a new set of time and date APIs under the package java.time. The following uses examples to explain to you the relevant knowledge of the new feature date API of java8. Friends who are interested should take a look.

Java 8 includes a new set of time and date APIs under the package java.time. The following example shows some of the most important parts of this new set of APIs:

1.Clock clock

The Clock class provides access to the current Date and time methods, Clock are time zone sensitive and can be used instead of System.currentTimeMillis() to get the current number of microseconds. A specific point in time can also be represented using the Instant class, which can also be used to create old java.util.Date objects.


Clock clock = Clock.systemDefaultZone();
long millis = clock.millis();
Instant instant = clock.instant();
Date legacyDate = Date.from(instant);  // legacy java.util.Date
Copy after login

2.Timezones Time zones

In the new API, time zones are represented by ZoneId. The time zone can be easily obtained using the static method of. The time zone defines the time difference to UTS time and is extremely important when converting between Instant Time objects and local date objects.


System.out.println(ZoneId.getAvailableZoneIds());
// prints all available timezone ids
ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");
System.out.println(zone1.getRules());
System.out.println(zone2.getRules());
// ZoneRules[currentStandardOffset=+01:00]
// ZoneRules[currentStandardOffset=-03:00]
Copy after login

3.LocalTime local time

LocalTime defines a time without time zone information, such as 10pm, or 17:30:15. The following example creates two local times using the time zone created by the previous code. The times are then compared and the time difference between the two times is calculated in hours and minutes:


LocalTime now1 = LocalTime.now(zone1);
LocalTime now2 = LocalTime.now(zone2);
System.out.println(now1.isBefore(now2)); // false
long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
System.out.println(hoursBetween);    // -3
System.out.println(minutesBetween);   // -239
Copy after login

LocalTime provides a variety of factory methods to simplify the creation of objects, including parsing time characters string.


LocalTime localTime= LocalTime.of(23, 59, 59);
System.out.println(localTime);    // 23:59:59
DateTimeFormatter germanFormatter =
  DateTimeFormatter
    .ofLocalizedTime(FormatStyle.SHORT)
    .withLocale(Locale.GERMAN);
LocalTime leetTime = localTime.format(germanFormatter);
System.out.println(leetTime);
Copy after login

4.LocalDate local date

LocalDate represents an exact date, such as 2014- 03-11. The object value is immutable and its use is basically the same as LocalTime. The following example shows how to add and subtract days/months/years to a Date object. Also note that these objects are immutable and operations always return a new instance.


LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
LocalDate yesterday = tomorrow.minusDays(2);
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek);  // FRIDAY
Copy after login

Parsing a LocalDate type from a string is as easy as parsing a LocalTime:


DateTimeFormatter germanFormatter =
  DateTimeFormatter
    .ofLocalizedDate(FormatStyle.MEDIUM)
    .withLocale(Locale.GERMAN);
LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
System.out.println(xmas);  // 2014-12-24
Copy after login

5.LocalDateTime Local date and time

LocalDateTime represents both time and date, which is equivalent to merging the contents of the first two sections into one object. LocalDateTime, like LocalTime and LocalDate, is immutable. LocalDateTime provides some methods to access specific fields.


LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
System.out.println(dayOfWeek);   // WEDNESDAY
Month month = sylvester.getMonth();
System.out.println(month);     // DECEMBER
long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
System.out.println(minuteOfDay);  // 1439
Copy after login

As long as the time zone information is appended, it can be converted into a point-in-time Instant object. The Instant-in-time object can be easily converted to the old-fashioned java.util. Date.


Instant instant = sylvester
    .atZone(ZoneId.systemDefault())
    .toInstant();
Date legacyDate = Date.from(instant);
System.out.println(legacyDate);   // Wed Dec 31 23:59:59 CET 2014
Copy after login

Formatting LocalDateTime is the same as formatting time and date. In addition to using the predefined format, we can also define the format ourselves:


DateTimeFormatter formatter =
  DateTimeFormatter
    .ofPattern("MMM dd, yyyy - HH:mm");
LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
String string = formatter.format(parsed);
System.out.println(string);   // Nov 03, 2014 - 07:13
Copy after login

Unlike java.text.NumberFormat, the new version of DateTimeFormatter is immutable, so it is thread-safe.

The above is the detailed content of Detailed example of the date API, a new feature in Java 8. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template