日期和现在之间的Java时间

时间:2011-09-03 17:29:40

标签: java date time

我需要帮助在Java中编写一个函数,它接受输入日期并告诉我自该日期以来的年,月和日数。

例如,“2005年7月1日”将输出“6年,2个月,2天”

2 个答案:

答案 0 :(得分:7)

使用Joda Time - 它相对容易:

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
    }
}

(我非常更喜欢Joda API到Date / Calendar。使用起来要容易得多,部分原因是通常更喜欢不变性。)

答案 1 :(得分:0)

java.time

下面引用的是来自 home page of Joda-Time 的通知:

<块引用>

请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - JDK 的核心部分,取代了该项目。

您可以使用 java.time.Period,它以 ISO-8601 standards 为模型,并作为 JSR-310 implementation 的一部分与 Java-8 一起引入。

使用 java.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);
    }
}

输出:

P6Y2M2D
6 years, 2 months, 2 days

ONLINE DEMO

Trail: Date Time 了解有关现代 Date-Time API 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

相关问题