period and duration test (#1795)

This commit is contained in:
lor6 2017-05-06 22:21:15 +03:00 committed by Grzegorz Piwowarek
parent 6bda038a28
commit 1e691b3a75
2 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,42 @@
package com.baeldung.dateapi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.junit.Test;
public class JavaDurationTest {
@Test
public void test2() {
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
Instant end = Instant.parse("2017-10-03T10:16:30.00Z");
Duration duration = Duration.between(start, end);
assertFalse(duration.isNegative());
assertEquals(60, duration.getSeconds());
assertEquals(1, duration.toMinutes());
Duration fromDays = Duration.ofDays(1);
assertEquals(86400, fromDays.getSeconds());
Duration fromMinutes = Duration.ofMinutes(60);
assertEquals(1, fromMinutes.toHours());
assertEquals(120, duration.plusSeconds(60).getSeconds());
assertEquals(30, duration.minusSeconds(30).getSeconds());
assertEquals(120, duration.plus(60, ChronoUnit.SECONDS).getSeconds());
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS).getSeconds());
Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
Duration fromChar2 = Duration.parse("PT10M");
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.dateapi;
import java.time.LocalDate;
import java.time.Period;
import org.apache.log4j.Logger;
import org.junit.Test;
import static org.junit.Assert.*;
public class JavaPeriodTest {
private static final Logger LOG = Logger.getLogger(JavaPeriodTest.class);
@Test
public void whenTestPeriod_thenOk() {
LocalDate startDate = LocalDate.of(2015, 2, 15);
LocalDate endDate = LocalDate.of(2017, 1, 21);
Period period = Period.between(startDate, endDate);
LOG.info("Years:" + period.getYears() + " months:" + period.getMonths() + " days:" + period.getDays());
assertFalse(period.isNegative());
assertEquals(56, period.plusDays(50).getDays());
assertEquals(9, period.minusMonths(2).getMonths());
Period fromUnits = Period.of(3, 10, 10);
Period fromDays = Period.ofDays(50);
Period fromMonths = Period.ofMonths(5);
Period fromYears = Period.ofYears(10);
Period fromWeeks = Period.ofWeeks(40);
assertEquals(280, fromWeeks.getDays());
Period fromCharYears = Period.parse("P2Y");
assertEquals(2, fromCharYears.getYears());
Period fromCharUnits = Period.parse("P2Y3M5D");
assertEquals(5, fromCharUnits.getDays());
}
}