What is temporal object in Java?

北城以北 提交于 2020-04-08 05:46:26

问题


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?


回答1:


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));
}



回答2:


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)).



来源:https://stackoverflow.com/questions/28229721/what-is-temporal-object-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!