Пример #1
1
 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);
 }
Пример #2
0
  public static Long getDiffMonths(Date one, Date two) {
    if (one.after(two)) {
      return getDiffMonths(two, one);
    }

    LocalDate startDate = one.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    LocalDate endDate = two.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

    return ChronoUnit.MONTHS.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));
  }