Subtract dates in JAVA in taking the difference of days

8

I need to calculate the day of pregnancy that a woman is, having the information of the date the woman became pregnant and the date today.

I have the following statement:

Date dtToday = new Date(); //pega a data de hoje
Data dtEngravidou = Mommy.getDtPregnantDate(); //retorna a data em que ficou grávida

In theory, I would need to subtract today's date with the date of pregnancy and I would have the number of days that have already passed, so I would have the difference, that is, how many days pregnant is my mother.     

asked by anonymous 01.07.2014 / 15:47

2 answers

8

You can do this using the DateTime and Duration of the JodaTime library.

import org.joda.time.DateTime;
import org.joda.time.Duration;

public class CalculaDiff {
    public static void main(String[] args) {
        DateTime dtToday = new DateTime(); //pega data e hora atual
        DateTime dtOther = new DateTime(DateTime.parse("2014-06-15T08:00:55Z")); //exemplo

        Duration dur = new Duration(dtOther, dtToday); //pega a duração da diferença dos dois

        System.out.println(dur.getStandardDays());
    }
}

Result:

  

16

You can download it here: Joda - Time

In this answer here has a good explanation of why not use the standard libraries.

    
01.07.2014 / 16:04
2

Now with the standard Java 8 APIs, you can do:

LocalDate dtToday = LocalDate().now();
LocalDate dtEngravidou = Mommy.getDtPregnantDate();
long diasDeGravidez = ChronoUnit.DAYS.between(dtEngravidou, dtToday);
System.out.println("Mamãe está grávida há " + diasDeGravidez + " dias");
    
02.02.2017 / 19:56