簡體   English   中英

日期和現在之間的Java時間

[英]Java Time between Date and Now

我需要幫助在Java中編寫一個函數,它接受輸入日期並告訴我自該日期以來的年,月和日數。

例如,“2005年7月1日”將輸出“6年,2個月,2天”

使用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 。它更容易使用,部分原因是通常更喜歡不變性。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM