如何在 Java 8 / jsr310 中格式化句点?

How to format a Period in Java 8 / jsr310?

我想在 Joda 时间格式化 Period using a pattern like YY years, MM months, DD days. The utilities in Java 8 are designed to format time but neither period, nor duration. There's a PeriodFormatter。 Java 是否有类似的实用程序?

一种解决方案是简单地使用 String.format:

import java.time.Period;

Period p = Period.of(2,5,1);
String.format("%d years, %d months, %d days", p.getYears(), p.getMonths(), p.getDays());

如果您确实需要使用DateTimeFormatter, you can use a temporary LocalDate, but this is a kind of hack that distort the semantic of LocalDate的功能。

import java.time.Period;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

Period p = Period.of(2,5,1);
DateTimeFormatter fomatter = DateTimeFormatter.ofPattern("y 'years,' M 'months,' d 'days'");
LocalDate.of(p.getYears(), p.getMonths(), p.getDays()).format(fomatter);

无需使用 String.format() 进行简单的字符串格式化。 JVM 将优化使用普通的旧字符串连接:

Function<Period, String> format = p -> p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days";
public static final String format(Period period){
    if (period == Period.ZERO) {
        return "0 days";
    } else {
        StringBuilder buf = new StringBuilder();
        if (period.getYears() != 0) {
            buf.append(period.getYears()).append(" years");
            if(period.getMonths()!= 0 || period.getDays() != 0) {
                buf.append(", ");
            }
        }

        if (period.getMonths() != 0) {
            buf.append(period.getMonths()).append(" months");
            if(period.getDays()!= 0) {
                buf.append(", ");
            }
        }

        if (period.getDays() != 0) {
            buf.append(period.getDays()).append(" days");
        }
        return buf.toString();
    }
}

正确的方法似乎是一个中间 LocalDate 对象然后调用 format

date1.format(DateTimeFormatter.ofPattern("uuuu MM LLLL ee ccc"));
OR (where appropriate)
date1.format(DateTimeFormatter.ofPattern("uuuu MM LLLL ee ccc", Locale.CHINA))

这会用中文打印 1997 01 一月 07 周六,用英语打印 1997 01 January 01 Sun,用荷兰语打印 1997 01 januari 07 zo

查看 "Patterns for Formatting and Parsing" 下的 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html 以获得您想要的格式。