Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Time between Date and Now

Tags:

java

date

time

I need help writing a function in Java that takes an input date and tells me the number of years, months, and days since the date.

For example, "July 1, 2005" would output "6 years, 2 months, 2 days"

like image 444
Richard Westington Avatar asked Mar 21 '26 03:03

Richard Westington


2 Answers

Use Joda Time - it makes it relatively easy:

import org.joda.time.*;

public class Test
{
    public static void main(String[] args)
    {
        LocalDate then = new LocalDate(2005, 7, 1);
        LocalDate today = new LocalDate();

        Period period = new Period(then, today, PeriodType.yearMonthDay());
        System.out.println(period); // P6Y2M2D
        System.out.println(period.getYears()); // 6
        System.out.println(period.getMonths()); // 2
        System.out.println(period.getDays()); //2
    }
}

(I vastly prefer the Joda API to Date/Calendar. It's much easier to use, partly due to generally preferring immutability.)

like image 71
Jon Skeet Avatar answered Mar 23 '26 19:03

Jon Skeet


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.

You can use java.time.Period which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation.

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

import java.time.LocalDate;
import java.time.Period;

public class Main {
    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2005, 7, 1);
        LocalDate endDate = LocalDate.of(2011, 9, 3);
        Period period = startDate.until(endDate);
        System.out.println(period);

        // Custom format
        String formatted = String.format("%d years, %d months, %d days", period.getYears(), period.getMonths(),
                period.getDays());
        System.out.println(formatted);
    }
}

Output:

P6Y2M2D
6 years, 2 months, 2 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.

like image 35
Arvind Kumar Avinash Avatar answered Mar 23 '26 17:03

Arvind Kumar Avinash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!