Do we have a TimeSpan sort of class in Java

前端 未结 4 1160
名媛妹妹
名媛妹妹 2020-11-29 08:59

I was just wondering if there is a need of TimeSpan in java.util so that I can define how much hours,minutes and seconds are there in between these two times.

4条回答
  •  感动是毒
    2020-11-29 09:22

    If you're on on Java 8 (or higher) or simply don't want to import JodaTime (the Author of JodaTime himself suggest migrating to java.time): Java 8 offers that functionality with Periods, see here for a tutorial: https://docs.oracle.com/javase/tutorial/datetime/iso/period.html

    Let me quote the Oracle tutorial here:

    LocalDate today = LocalDate.now();
    LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
    
    Period p = Period.between(birthday, today);
    long p2 = ChronoUnit.DAYS.between(birthday, today);
    System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
                       " months, and " + p.getDays() +
                       " days old. (" + p2 + " days total)");
    

    The code produces output similar to the following:

    You are 53 years, 4 months, and 29 days old. (19508 days total)
    

提交回复
热议问题