1

I have some Java code which returns the ISO-8601 time format from a given epoch time.

public String getISO8601(String epochTime) {
    long epoch = Long.parseLong(epochTs);
    ZoneId zone = ZoneId.of("Europe/London");
    LocalDate then = Instant.ofEpochMilli(epoch).atZone(zone).toLocalDate();
    LocalDate today = LocalDate.now(zone);
    Period diff = Period.between(then, today);
    return diff.toString();
}

When I pass epochTime to it: 1512259200000

This epoch time is: Sun 2017-12-03 00:00:00

So the method getISO8601 will return: P1Y

This is great! But is there any way I can make sure it will always and only return in days... for example: P365D (instead of: P1Y)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Saffik
  • 911
  • 4
  • 19
  • 45
  • Possible duplicate of [How to calculate the number of days in a period?](https://stackoverflow.com/questions/30833582/how-to-calculate-the-number-of-days-in-a-period) – Glains Dec 03 '18 at 11:20

3 Answers3

5

Unfortunately Period doesn't allow the units to be specified, but you can use the until method to handle this, specifying you want the difference in days:

public static Period getPeriodInDaysBetween(LocalDate from, LocalDate to) {
    int days = (int) from.until(to, ChronoUnit.DAYS);
    return Period.ofDays(days);
}

Use that instead of Period.between and it'll do what you want, I believe.

(The first line is equivalent to the ChronoUnit.DAYS.between(date1, date2) in MS90's answer. Use whichever you find more readable.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Sure, take a look at following code:

   public static long countDays(LocalDate date1, LocalDate date2) {

        long daysInAPeriod = ChronoUnit.DAYS.between(date1, date2);
        return daysInAPeriod;
    }
MS90
  • 1,219
  • 1
  • 8
  • 17
-1

Period has a getDays method which returns an int number of days in the Period.