public String getTimeSinceUploaded() { String unit = ""; LocalDateTime now = LocalDateTime.now(); long diff; if ((diff = ChronoUnit.SECONDS.between(dateUploaded, now)) < 60) { unit = "secs"; } else if ((diff = ChronoUnit.MINUTES.between(dateUploaded, now)) < 60) { unit = "mins"; } else if ((diff = ChronoUnit.HOURS.between(dateUploaded, now)) < 24) { unit = "hours"; } else if ((diff = ChronoUnit.DAYS.between(dateUploaded, now)) < 30) { unit = "days"; } else if ((diff = ChronoUnit.MONTHS.between(dateUploaded, now)) < 12) { unit = "months"; } else { diff = ChronoUnit.YEARS.between(dateUploaded, now); } return String.format("%d %s", diff, unit); }
public Integer calculateAge() { LocalDate dateOfBirth = this.getDateOfBirth(); LocalDate now = LocalDate.now(); if (dateOfBirth == null) return null; Long age = ChronoUnit.YEARS.between(dateOfBirth, now); return Math.abs((int) (long) age); }
/** * 返回one和two之间年的差距,以one为基准,每七天+1 * * @param one * @param two * @return */ public static Long getDiffYears(Date one, Date two) { if (one.after(two)) { return getDiffYears(two, one); } LocalDate startDate = one.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate endDate = two.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); return ChronoUnit.YEARS.between(startDate, endDate); }
public static void main(String[] args) { LocalDateTime date1 = LocalDateTime.of(LocalDate.of(1999, 5, 15), LocalTime.of(10, 22)); LocalDateTime date2 = LocalDateTime.of(LocalDate.of(2008, 2, 11), LocalTime.of(5, 33)); System.out.println("date1: " + date1); System.out.println("date2: " + date2); System.out.println(ChronoUnit.YEARS.between(date1, date2)); System.out.println(ChronoUnit.MONTHS.between(date1, date2)); System.out.println(ChronoUnit.WEEKS.between(date1, date2)); System.out.println(ChronoUnit.DAYS.between(date1, date2)); System.out.println(ChronoUnit.HOURS.between(date1, date2)); System.out.println(ChronoUnit.MINUTES.between(date1, date2)); System.out.println(ChronoUnit.SECONDS.between(date1, date2)); }