java - 什么是 Java 中的时间对象?

标签 java java-8

我正在探索 TemporalQueryTemporalAccessor在 Java 8 中引入。TemporalAccessor 似乎是专门为时间对象(例如日期、时间、偏移量或它们的某种组合)设计的。什么是临时对象? 一些谷歌搜索给出了它的意思

An object that changes over time

但无法在 Java 的上下文中关联它?

最佳答案

根据 Joda-Time 和 JSR 310,问题、概念和方法 [PDF] , TemporalAccessor:

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

JSR-310 Date and Time API Guide状态:

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

本书Beginning Java 8 Fundamentals: Language Syntax, Arrays, Data Types, Objects, and Regular Expressions说:

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.

接下来是示例代码(基于前一本书中的一些示例):

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

关于java - 什么是 Java 中的时间对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28229721/

相关文章:

java - 转换 Arrays.asList 导致异常 : java. util.Arrays$ArrayList 无法转换为 java.util.ArrayList

java - 拆分返回 PatternSyntaxException : Illegal/unsupported escape sequence

java - 如果我使用 Java 8 的 String.codePoints 获取一个 int codePoints 数组,数组的长度是字符数吗?

java - 将 LocalDateTime 转换为 UTC 中的 LocalDateTime

Java 8 Streams减少删除重复项并保留最新条目

java - 将 JDialog 转换为 Jframe/JPanel

java - 如何检查 Java 2d 数组 Tic Tac Toe 中的垂直和对角获胜

java - 搜索给定目录和文件名的特定文件,向下查找目录并发送其路径

java - 是否可以使用 Java 8 将日期截断为月份?

Maven + AspectJ 织入 Java8