代码之家  ›  专栏  ›  技术社区  ›  naXa stands with Ukraine

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

  •  21
  • naXa stands with Ukraine  · 技术社区  · 7 年前

    我想格式化一个文件 Period 使用像这样的模式 YY years, MM months, DD days . Java8中的实用程序设计用于格式化时间,但既不是周期,也不是持续时间。有一个 PeriodFormatter 在乔达时代。Java有类似的实用程序吗?

    4 回复  |  直到 7 年前
        1
  •  15
  •   Ortomala Lokni    7 年前

    一种解决方法是简单地使用 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 ,您可以使用临时 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);
    
        2
  •  4
  •   Oleg Cherednik    7 年前

    没有必要使用 String.format() 用于简单的字符串格式设置。JVM将优化使用普通旧字符串连接:

    Function<Period, String> format = p -> p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days";
    
        3
  •  2
  •   Luk    7 年前
    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();
        }
    }
    
        4
  •  0
  •   RecurringError    7 年前

    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

    退房 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html 在“格式化和解析模式”下,查看所需格式。