Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java8/jsr310中格式化句点?_Java_Java 8_Period_Time Format - Fatal编程技术网

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

如何在Java8/jsr310中格式化句点?,java,java-8,period,time-format,Java,Java 8,Period,Time Format,我想使用类似于YY年、MM月、DD天的模式格式化一个文件。Java8中的实用程序设计用于格式化时间,但既不是周期,也不是持续时间。在乔达的时间里有一段时间。Java有类似的实用程序吗?一种解决方案是简单地使用: 如果您真的需要使用的功能,您可以使用临时的,但这是一种扭曲的语义 对于简单的字符串格式,不需要使用String.format()。JVM将优化使用普通旧字符串连接: Function<Period, String> format = p -> p.getYears()

我想使用类似于
YY年、MM月、DD天的模式格式化一个文件。Java8中的实用程序设计用于格式化时间,但既不是周期,也不是持续时间。在乔达的时间里有一段时间。Java有类似的实用程序吗?

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

如果您真的需要使用的功能,您可以使用临时的,但这是一种扭曲的语义


对于简单的字符串格式,不需要使用
String.format()
。JVM将优化使用普通旧字符串连接:

Function<Period, String> format = p -> p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days";
Function format=p->p.getYears()+“年”、+p.getMonths()+“月”、+p.getDays()+“天”;

正确的方法似乎是使用中间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年1月1日星期日
英文和
1997年1月7日zo
荷兰语


在“格式化和解析模式”下查看您想要的格式。

我不喜欢看到
LocalDate
被用作黑客。为什么不使用Java中的字符串功能使用相同的占位符和值替换方法呢?我同意扭曲
LocalDate
的语义并不优雅,可能会导致问题。@BasilBourque我大体上同意,但在我看来,这是解决JDK Api弱点的一个方法,这应该允许
DateTimeFormatter
接受任何
TemporalAmount
。问题在于(Joda解决的)字符串没有本地化。不,java.time没有类似的功能。只是想知道在这种情况下普通的旧方法声明会有什么问题?就我个人而言,我认为在这种情况下,
String.format()
版本更容易阅读。
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();
    }
}
date1.format(DateTimeFormatter.ofPattern("uuuu MM LLLL ee ccc"));
OR (where appropriate)
date1.format(DateTimeFormatter.ofPattern("uuuu MM LLLL ee ccc", Locale.CHINA))