Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is temporal object in Java?

Tags:

java

java-8

I was exploring TemporalQuery and TemporalAccessor introduced in Java 8. TemporalAccessor seems to be specially designed for temporal objects such as date, time, offset or some combination of these . What are temporal objects? Some googling gave its meaning as

An object that changes over time

But not able to relate this in the context of Java?

like image 914
Omkar Shetkar Avatar asked Jan 30 '15 05:01

Omkar Shetkar


2 Answers

According to with Joda-Time & JSR 310, Problems, Concepts and Approaches [PDF], the TemporalAccessor:

Defines read-only access to a temporal object, such as a date, time, offset or some combination of these

The JSR-310 Date and Time API Guide states:

Fields and units work together with the abstractions Temporal and TemporalAccessor provide access to date-time classes in a generic manner.

The book Beginning Java 8 Fundamentals: Language Syntax, Arrays, Data Types, Objects, and Regular Expressions says:

All classes in the API that specify some kind of date, time, or both are TemporalAccesor. LocalDate, LocalTime, LocalDateTime, and ZoneDateTime are some examples of TemporalAccesor.

The next is a example code (based from some examples in the previous book):

public static boolean isFriday13(TemporalAccessor ta) {
    if (ta.isSupported(DAY_OF_MONTH) && ta.isSupported(DAY_OF_WEEK)) {
        int dayOfMonth = ta.get(DAY_OF_MONTH);
        int weekDay = ta.get(DAY_OF_WEEK);
        DayOfWeek dayOfWeek = DayOfWeek.of(weekDay);
        if (dayOfMonth == 13 && dayOfWeek == FRIDAY) {
            return true;
        }
    }
    return false;
}

public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    TemporalAccessor ta = formatter.parse("02/13/2015");
    LocalDate ld = LocalDate.from(ta);
    System.out.println(ld);
    System.out.println(isFriday13(ld));
}
like image 68
Paul Vargas Avatar answered Oct 03 '22 18:10

Paul Vargas


Temporal Objects are basically the objects which have different related values like for example last day of the month", or "next Wednesday" etc in context of date object. In Java8 These are modeled as functions that adjust a base date-time.The functions implement TemporalAdjuster and operate on Temporal. For example, to find the first occurrence of a day-of-week after a given date, use TemporalAdjusters.next(DayOfWeek), such as date.with(next(MONDAY)).

like image 36
Vivek Mishra Avatar answered Oct 03 '22 19:10

Vivek Mishra