コード例 #1
0
  @Override
  public String convert(LocalDateTime dateTime) {
    LocalDateTime now = LocalDateTime.now();
    Duration duration = Duration.between(dateTime, now);

    Period period = Period.between(dateTime.toLocalDate(), now.toLocalDate());

    if (duration.toMinutes() < 1) {
      return String.format("%s secs ago", duration.getSeconds());
    }

    if (duration.toHours() < 1) {
      return String.format("%s mins ago", duration.toMinutes());
    }

    if (duration.toDays() < 1) {
      return String.format("%s hrs ago", duration.toHours());
    }

    if (period.getYears() > 0) {
      return DateTimeFormatter.ISO_LOCAL_DATE.format(dateTime);
    }

    if (period.getMonths() > 0) {
      return String.format("%s months ago", period.getMonths());
    }

    return String.format("%s days ago", period.getDays());
  }
コード例 #2
0
 @Test
 public void testGetAge() {
   LocalDate now = LocalDate.now();
   int currentYear = now.getYear();
   LocalDate birthDate = LocalDate.of(2010, 2, 1);
   Period age = AgeUtils.getAge(birthDate); // P6Y1M21D
   Assert.assertEquals(currentYear - birthDate.getYear(), age.getYears());
   Assert.assertEquals(now.getMonthValue() - birthDate.getMonthValue(), age.getMonths());
   Assert.assertEquals(now.getDayOfMonth() - birthDate.getDayOfMonth(), age.getDays());
 }
コード例 #3
0
  @Test
  public void testGetAgeDetails() {
    LocalDate to = LocalDate.of(2011, 1, 10);

    LocalDate from = LocalDate.of(2010, 1, 10);
    Period age = AgeUtils.getAge(from, to);
    Assert.assertEquals(1, age.getYears());
    Assert.assertEquals(0, age.getMonths());
    Assert.assertEquals(0, age.getDays());

    from = LocalDate.of(2010, 1, 11);
    age = AgeUtils.getAge(from, to);
    Assert.assertEquals(0, age.getYears());
    Assert.assertEquals(11, age.getMonths());
    Assert.assertEquals(30, age.getDays());

    from = LocalDate.of(2010, 5, 11);
    age = AgeUtils.getAge(from, to);
    Assert.assertEquals(0, age.getYears());
    Assert.assertEquals(7, age.getMonths());
    Assert.assertEquals(30, age.getDays());
  }