Java 8 - Date API
Hi, I am Malathi Boggavarapu working at Volvo Group and i live in Gothenburg, Sweden. I have been working on Java since several years and had vast experience and knowledge across various technologies.
This course teach you about Date API in Java8.
Date API in java8
java.time - completly replaces java.util and Calendar classes and still keeps inter-operability with legacy APIInstant - It is a class and is a point on the timeline
Timeline - Assume it is line of time with dates on it and it has given precision and precision is the nanosecond.Conventions of instant class
Instant 0 is the January the 1st, 1970 at midnight GMTInstant.MIN is 1 billion years ago
Instant.MAX is Dec 31 of the year 1,000,000,000
Instant.now() is the current instant
The timeline begins from 1 billion years ago and end with 1 billion years from now.
Precision of the time would be in the nanosecond
Instant object is immutable
Instant start = Instant.now();
.......
Instant end = Instant.now();
Duration
Duration gives the elapsed time between two Instant objectsDuration elapsed = Duration.between(start, end);
long mills = elapsed.toMillis();
Methods
--------
toNanos(), toMillis(), toSeconds(), toMinues(), toHours(), toDays() - Used to convert duration between two instant objects to nano seconds, milli seconds, seconds, minuets, hours and days
minusNanos() - Used to add some nano seconds to the duration
plusNanos() - Used to add some nano seconds to the duration
multipliedBy(), dividedBy(), negated() - Used to multiply or divide the duration with a number
isZero(), isNegative() - Check whether the duration is zero or negative
There are many cases where date is not an Instant
Ex: Shakespere was born Apr 23, 1564
Let us meet at 1Pm and have lunch together
In the first example, it is just a date without nanosecond precision but Instant represents a date with nanoseconds precision. So Instant is not suitable for such dates without nanosecond precision
The same applies to Example 2. It just says at 1PM, the hour of the day.
So we need another concept for those dates. LocaDate is used for that.
LocalDate
LocalDate is used to create a date without requiring precision like Instant class. So the above examples could be addressed using the LocalDate class.LocalDate now = LocalDate.now();
LocalDate dateOfBirth = LocalDate.of(1564, Month.APRIL, 23)
Here if you see we represent Month using Month.APRIL which is more readable. But in Java 7, it should represent month as 3 which is April.
Period
The Period is the amount of time between two LocalDate whereas Duration is the amount of time between two Instant objectsExample: When was shakesphere was born?
Period p = dateOfBirth.until(now);
System.out.println("# years "+ p.getYears());
long days = dateOfBirth.until(now, ChronoUnit.DAYS);
System.out.println("# days "+ days);
Example
People.txt
Malathi 1984 05 18
Naresh 1983 10 01
Neelima 1980 10 20
DateAndTime.java
List<Person> persons = new ArrayList();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(DateAndTime.class.getResourceAsStream("People.txt")));
Stream<String> stream = reader.lines();
stream.map(line -> {
String s[] = line.split(" ");
String name = s[0]
int year = Integer.parseInt(s[1]);
Month month = Month.of(Integer.parseInt(s[2]));
int day = Integer.parseInt(s[3]);
Person p = new Person(name, LocalDate(year, month, day));
persons.add(p);
return p;
}).forEach(System.out::println);
LocalDate now = LocalDate.of(12, Month.MARCH, 2014);
persons.stream().forEach(p -> {
Period period = Period.between(p.getDateOfBirth(), now);
System.out.println(p.getName() + "was born " +
period.get(ChronoUnit.YEARS) + "years and " +
period.get(ChronoUnit.MONTHS) + "months " +
"[" + p.getDateOfBirth().until(now, ChronoUnit.MONTHS) + " months]"
);
}
);
}
Person.java
public class Person{
private String name;
private LocalDate dateOfBirth;
public void Person(String name, LocalDate dateOfBirth){
this.name = name;
this.dateOfBirth = dateOfBirth;
}
// getter and setter methods for name and LocalDate
}
The above example reads the input from Persons.txt file which contains Person name, Year, Month, Day. Using Stream API , LocalDate and Period classes we compare the date of birth of a person and current date and extract number of years, months and number of months since the Person is born.
Hope the above example is useful to easily understand.
DateAdjuster
Useful to add or subtract an amount of time to an instant or a LocalDateLocalDate now = LocalDate.now();
LocalDate nextSunday = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
See more in javadoc for more methods available for TemporalAdjusters class
LocalTime
It is just a time in the day.Ex: 10:20
LocalTime now = LocalTime.now();
LocalTime time = LocalTime.of(10, 20) //10:20
we have set of methods available to manipulate that time
LocalTime time = LocalTime.of(10, 20)
LocalTime wakeupTime = time.plusHours(8); 10:20 + 8hours
Zoned Time
There are Time zones all over the earthThe zones are available from
Set<String> allZoneIds = ZoneId.getAvailableZoneIds();
String uKTZ = ZoneId.of("Europe/London");
Example
System.out.println(
ZonedDateTime.of(
1564, Month.APRIL.getValue(), 23, //year, month, day
10, 0, 0, 0, // h/mm/s/nanos
ZoneId.of("Europe/London"))
); // prints 1564-04-23T10:00-00:01:15[Europe/London]
See more methods available in javadoc
DateTimeFormatter
---------------------------
check javadoc...
Bridges between legacy (java 1 API inherited to java7)
How to interoperate with the legacy Date API from java 7? We have certain methods available to provide inter-operability between Java 7 date API (legacy API ) and Java 8 API.1) Instant and Date
Date date = Date.from(instant); // Java 8 to legacy code (old java version API)
Instant instant = date.toInstant(); // legacy code to Java 8
2) Instant and TimeStamp
TimeStamp time = TimeStamp.from(instant); // Java 8 to legacy code (old java version API)
Instant instant = time.toInstant(); // legacy code to Java 8
3) LocalDate and Date
Date date = Date.from(localDate); // Java 8 to legacy code (old java version API)
LocalDate localDate = date.toLocalDate(); // legacy code to Java 8
4) LocalDate and Time
Time time = Time.from(localTime); // Java 8 to legacy code (old java version API)
LocalTime localTime = time.toLocalTime(); // legacy code to Java 8
Comments
Post a Comment