Java 中的当前日期和时间

Current date and time in Java

以这种格式 return 当前日期和时间的最佳方式是什么?

2021-05-16T09:20:47-05:00

目前我正在这样做:

SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
strDate = formatter.format(date);

但我相信有更好的方法可以完成我正在尝试的事情。

编辑:

OffsetDateTime.now() 完成任务。

尝试使用(自 Java 8)用 DateTimeFormatter 格式化的 ZonedDateTime。 可以使用 DateTimeFormatterBuilder 创建和配置 DateTimeFormatter 对象 class:

System.out.println(ZonedDateTime.now()
                     .format(new DateTimeFormatterBuilder()
                                  .append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
                                  .appendOffsetId()
                                  .toFormatter()));

java.time.OffsetDateTime

与其他人一样,我明确建议您使用 java.time,现代 Java 日期和时间 API,作为您的日期和时间 work.The class 你需要一个带有偏移量的日期和时间,例如 -05:00 是 OffsetDateTime(并不奇怪,是吗?)

    ZoneId zone = ZoneId.of("America/Monterrey");
    OffsetDateTime currentDateAndTime = OffsetDateTime.now(zone);
    System.out.println(currentDateAndTime);

我运行刚才的代码时输出:

2021-04-26T13:22:05.246327-05:00

如果您想要自己时区的偏移量,请将 zone 设置为 ZoneId.systemDefault()

我正在利用您要求 ISO 8601 格式和 java.time 的 classes 从他们的 toString 方法生成 ISO 8601 格式的事实,因此没有任何明确的格式化程序.

因此,如果您需要 String,它只是:

    String currentDateAndTimeString = currentDateAndTime.toString();
    System.out.println(currentDateAndTimeString);

输出与之前相同。

如果你需要一个有秒但没有小数秒的字符串——你很可能不需要。正如我所写,您要求的格式是 ISO 8601,根据 ISO 8601 标准,秒和秒的小数部分是可选的,当它们不存在时被理解为零。因此,假设您需要此字符串用于外部服务或其他需要 ISO 8601 的组件,上面的字符串就可以了。在任何情况下:编辑:截断秒的分数并使用标准格式化程序:

    String currentDateAndTimeWithSecondsOnly = currentDateAndTime
            .truncatedTo(ChronoUnit.SECONDS)
            .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    System.out.println(currentDateAndTimeWithSecondsOnly);

刚才运行时输出:

2021-04-26T23:53:22-05:00

DateTimeFormatter.ISO_OFFSET_DATE_TIME 将输出秒,即使它们为零,也会在秒为零时忽略秒的小数部分(我需要非常仔细地阅读文档才能理解这一点)。

链接