0

In this part of my code I want Joda Time to calculate and show how much time left until next birthday. So the year should change on birthday

DateTime startDate = DateTime.now();
DateTime endDate = new DateTime(x,m110,d110,h120,min120);
Period period = new Period(startDate, endDate, PeriodType.dayTime());
textView3.setText(formatter.print(period));
PeriodFormatter formatter = new PeriodFormatterBuilder()
                    .appendMonths().appendSuffix(".")
                    .appendDays().appendSuffix(" ")
                    .appendHours().appendSuffix(":")
                    .appendMinutes().appendSuffix(":")
                    .appendSeconds()
                    .toFormatter();

x here is year, m110, d110, h120, min120 - month, day, hour and minute. What should I write instead of "x", so it could count how much time left every year and not once. And another question. When it's, for example, 3 hours, 4 minutes, what should I do in order to display "03:04:00" instead of "3:4:" (it also just doesn't show 0)

flo
  • 9,713
  • 6
  • 25
  • 41

1 Answers1

0

The value of x is dependent of whether the birthday has already happend this year or not. You can check this using DateTime.before methods on the same day and month in the current year:

DateTime startDate = DateTime.now();
int year = startDate.getYear();
DateTime endDate = new DateTime(year,m110,d110,h120,min120);
if (endDate.isBefore(startDate)) // birthday happend already this year?
    endDate = endDate.plusYears(1); // then the next one is in the next year

As for your second question: You can advice the builder to create a formatter which always prints zeros using printZeroAlways(). To get the formatter to print at least two digits you can use the minimumPrintedDigits method:

   PeriodFormatter formatter = new PeriodFormatterBuilder()            
        .minimumPrintedDigits(0)

        .appendMonths().appendSuffix(".")
        .printZeroAlways()
        .appendDays().appendSuffix(" ")

        .minimumPrintedDigits(2)

        .appendHours().appendSuffix(":")
        .appendMinutes().appendSuffix(":")
        .appendSeconds()
        .toFormatter();

Note that those methods only apply to the fields added after the invocation of the method. Also, the value may change along the builder's creation several times.

flo
  • 9,713
  • 6
  • 25
  • 41