1

I have two DateTimes, one is the time 'since' and 'now'

What I need, is get the time between then.

My problem is into the format I want to get it:

Example: since = '17 april 2010' now = '15 april 2011'

I want to have '0 years, 11 months, 29 days'

And in case since is '13 april 2010' the result should be like: '1 years, 0 months, 2 days'

But this logic is puzzling me.

JodaStephen
  • 60,927
  • 15
  • 95
  • 117
Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167

2 Answers2

4

I'm not entirely sure I follow your question. It sounds like you want:

DateTime since = ...;
DateTime now = ...;

Period period = new Period(since, now, PeriodType.yearMonthDay());
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();

If that isn't the case, could you give more details?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

java.time

Quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

  1. Use Period#between to get the period between two LocalDates.
  2. Note that the month name in your string is in lowercase and therefore, you will need to build the DateTimeFormatter using parseCaseInsensitive function.
  3. Never use DateTimeFormatter without a Locale.

Demo:

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                .parseCaseInsensitive()
                                .appendPattern("d MMMM uuuu")
                                .toFormatter(Locale.ENGLISH);
        
        LocalDate since = LocalDate.parse("17 april 2010", dtf);
        LocalDate now = LocalDate.parse("15 april 2011", dtf);
        
        Period period = Period.between(since, now);
        
        String strPeriod = String.format("%d years %d months %d days", period.getYears(), period.getMonths(),
                period.getDays());
        System.out.println(strPeriod);
    }
}

Output:

0 years 11 months 29 days

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110