Convert seconds to years/days/hours/minutes automatically, using JodaTime?

java, jodatime

Solution

I'm not sure why you don't want to specify what you need in `PeriodFormatter`. `JodaTime` doesn't know how you want to display a period as a string, so you need to tell it via the `PeriodFormatter`.

As 3600 seconds is 1 hour, using the formatter properly will automatically do this for you. Here's a code example using a number of different inputs on the same formatter which should achieve your desired result.

    Seconds s1 = Seconds.seconds(3601);
    Seconds s2 = Seconds.seconds(2000);
    Seconds s3 = Seconds.seconds(898298);
    Period p1 = new Period(s1);
    Period p2 = new Period(s2);
    Period p3 = new Period(s3);
    
    PeriodFormatter dhm = new PeriodFormatterBuilder()
        .appendDays()
        .appendSuffix(" day", " days")
        .appendSeparator(" and ")
        .appendHours()
        .appendSuffix(" hour", " hours")
        .appendSeparator(" and ")
        .appendMinutes()
        .appendSuffix(" minute", " minutes")
        .appendSeparator(" and ")
        .appendSeconds()
        .appendSuffix(" second", " seconds")
        .toFormatter();
    
    System.out.println(dhm.print(p1.normalizedStandard()));
    System.out.println(dhm.print(p2.normalizedStandard()));
    System.out.println(dhm.print(p3.normalizedStandard()));

Produces output::

1 hour and 1 second

33 minutes and 20 seconds

3 days and 9 hours and 31 minutes and 38 seconds

Problem

Is there way to convert 'x' seconds to y hours and z seconds when say x exceeds 3600 seconds? Similarly, convert it to 'a minutes and b seconds' when x exceeds 60 but is less than 3600 seconds, using JodaTime? I understand that I would have to specify what I need in the PeriodFormatter, but I don't want to specify it - I want a formatted text based on value of seconds. This is similar to how you would post on a forum and then your post will initially be shown as 'posted 10 seconds ago'.. after 1 minute you would see 'posted 1minute 20 seconds ago' and likewise for weeks,days,years.

Original source