0

I would like to format a period (age) in human readable form like:

47 years, one month and 7 days. Here 1 replaced by one and 0 skipped like 58 years and 7 days.

Is there a ready-made formatter for such a task? Should I write my own and how to do this properly? Do I have to use Format abstract class?

Jegors Čemisovs
  • 608
  • 6
  • 14
  • 2
    The `DateTimeFormatterBuilder` is built in to Java but it's not flexible enough for your use. You could extend `DataTimeFormatter` though you would still need to write the logic yourself. – sprinter Aug 18 '21 at 23:32
  • check this https://stackoverflow.com/questions/53749850/how-to-format-a-period-in-java-8-jsr310 you would need to do little modification to it to remove any 0 value –  Aug 18 '21 at 23:32
  • I read mentioned post before I publish my question. I suppose that I have to write my own logic. I wondering how I can do it in optimal way. – Jegors Čemisovs Aug 18 '21 at 23:44
  • 1
    I can't extend `public final class DateTimeFormatter` – Jegors Čemisovs Aug 18 '21 at 23:46
  • 1
    I think you will need to start from scratch. You don't have to use any specific base class or interface. For requirements as "off beat" as this (i.e. spelling out numbers as words in an apparently inconsistent way) it is unclear that existing Java formatting APIs are going to help you. In this case, "properly" is going to be subjective ... and irrelevant. – Stephen C Aug 19 '21 at 04:46

1 Answers1

0

Sharing the input will help a lot. you can prepare a Map and String.format method here to accomplish your goal. Assuming you already have a logic in place to calculate month, days, and year.

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "one");
        map.put(2, "two");
        map.put(3, "three");
        map.put(4, "four");
        map.put(5, "five");
        map.put(6, "six");
        map.put(7, "seven");
        map.put(8, "eight");
        map.put(9, "nine");
        map.put(10, "ten");
        map.put(11, "eleven");

String.format("%d years, %s month and %d days", "variable that stores year", "variable that stores month", "variable for days");

Dharman
  • 30,962
  • 25
  • 85
  • 135
vaibhavsahu
  • 612
  • 2
  • 7
  • 19