java.time.temporal.TemporalAmount Java Examples

The following examples show how to use java.time.temporal.TemporalAmount. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TCKChronoZonedDateTime.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="calendars")
public void test_badPlusAdjusterChrono(Chronology chrono) {
    LocalDate refDate = LocalDate.of(2013, 1, 1);
    ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
    for (Chronology[] clist : data_of_calendars()) {
        Chronology chrono2 = clist[0];
        ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
        TemporalAmount adjuster = new FixedAdjuster(czdt2);
        if (chrono != chrono2) {
            try {
                czdt.plus(adjuster);
                Assert.fail("WithAdjuster should have thrown a ClassCastException, "
                        + "required: " + czdt + ", supplied: " + czdt2);
            } catch (ClassCastException cce) {
                // Expected exception; not an error
            }
        } else {
            // Same chronology,
            ChronoZonedDateTime<?> result = czdt.plus(adjuster);
            assertEquals(result, czdt2, "WithAdjuster failed to replace date time");
        }
    }
}
 
Example #2
Source File: TCKChronoZonedDateTime.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="calendars")
public void test_badMinusAdjusterChrono(Chronology chrono) {
    LocalDate refDate = LocalDate.of(2013, 1, 1);
    ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
    for (Chronology[] clist : data_of_calendars()) {
        Chronology chrono2 = clist[0];
        ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
        TemporalAmount adjuster = new FixedAdjuster(czdt2);
        if (chrono != chrono2) {
            try {
                czdt.minus(adjuster);
                Assert.fail("WithAdjuster should have thrown a ClassCastException, "
                        + "required: " + czdt + ", supplied: " + czdt2);
            } catch (ClassCastException cce) {
                // Expected exception; not an error
            }
        } else {
            // Same chronology,
            ChronoZonedDateTime<?> result = czdt.minus(adjuster);
            assertEquals(result, czdt2, "WithAdjuster failed to replace date");
        }
    }
}
 
Example #3
Source File: TCKChronoLocalDate.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="calendars")
public void test_badMinusAdjusterChrono(Chronology chrono) {
    LocalDate refDate = LocalDate.of(2013, 1, 1);
    ChronoLocalDate date = chrono.date(refDate);
    for (Chronology[] clist : data_of_calendars()) {
        Chronology chrono2 = clist[0];
        ChronoLocalDate date2 = chrono2.date(refDate);
        TemporalAmount adjuster = new FixedAdjuster(date2);
        if (chrono != chrono2) {
            try {
                date.minus(adjuster);
                Assert.fail("WithAdjuster should have thrown a ClassCastException");
            } catch (ClassCastException cce) {
                // Expected exception; not an error
            }
        } else {
            // Same chronology,
            ChronoLocalDate result = date.minus(adjuster);
            assertEquals(result, date2, "WithAdjuster failed to replace date");
        }
    }
}
 
Example #4
Source File: TimeParserTest.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Test the times Duration ← relative
 */
@Test
public void getDuration() {
    // "last min", "last hour", "last day", "last week"
    Duration lastMin = TimeParser.parseDuration("1 min");
    assertEquals("Failed to get Duration for last min", Duration.ofSeconds(60),
            lastMin);
    Duration lastHour = TimeParser.parseDuration("1 hour");
    assertEquals("Failed to get Duration for last hour",
            Duration.ofHours(1), lastHour);
    // "last 5 mins", "last 5 hours", "last 5 days"
    TemporalAmount last5Min = TimeParser.parseDuration(" 5 mins");
    assertEquals("Failed to get Duration for last 5 mins",
            Duration.ofMinutes(5), last5Min);
    TemporalAmount last5Hour = TimeParser.parseDuration(" 5 hours");
    assertEquals("Failed to get Duration for last 5 hours",
            Duration.ofHours(5), last5Hour);
    Duration last5Day = TimeParser.parseDuration(" 5 days");
    assertEquals("Failed to get Duration for last 5 days",
            60 * 60 * 24 * 5, last5Day.getSeconds());
}
 
Example #5
Source File: TCKChronoZonedDateTime.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="calendars")
public void test_badPlusAdjusterChrono(Chronology chrono) {
    LocalDate refDate = LocalDate.of(2013, 1, 1);
    ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
    for (Chronology[] clist : data_of_calendars()) {
        Chronology chrono2 = clist[0];
        ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
        TemporalAmount adjuster = new FixedAdjuster(czdt2);
        if (chrono != chrono2) {
            try {
                czdt.plus(adjuster);
                Assert.fail("WithAdjuster should have thrown a ClassCastException, "
                        + "required: " + czdt + ", supplied: " + czdt2);
            } catch (ClassCastException cce) {
                // Expected exception; not an error
            }
        } else {
            // Same chronology,
            ChronoZonedDateTime<?> result = czdt.plus(adjuster);
            assertEquals(result, czdt2, "WithAdjuster failed to replace date time");
        }
    }
}
 
Example #6
Source File: ScheduleUtils.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Create a schedule to run a task exactly once at the given time.
 * for a service with given name and relinquishing leadership
 * at a given interval
 *
 * @param instant the task will run
 * @param taskName name of the task in the global world
 * @param number period to release leadership
 * @param timeUnit time unit to release leadership
 * @return schedule with the time in millis
 */
public static Schedule scheduleForRunningOnceAt(final Instant instant, final String taskName,
                                                long number, TimeUnit timeUnit) {
  return new Schedule() {
    @Override
    public TemporalAmount getPeriod() {
      return null;
    }

    @Override
    public Iterator<Instant> iterator() {
      return Collections.singletonList(instant)
        .iterator();
    }

    @Override
    public String getTaskName() {
      return taskName;
    }

    @Override
    public Long getScheduledOwnershipReleaseInMillis() {
      return timeUnit.toMillis(number);
    }
  };
}
 
Example #7
Source File: TCKChronoZonedDateTime.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="calendars")
public void test_badPlusAdjusterChrono(Chronology chrono) {
    LocalDate refDate = LocalDate.of(2013, 1, 1);
    ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
    for (Chronology[] clist : data_of_calendars()) {
        Chronology chrono2 = clist[0];
        ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
        TemporalAmount adjuster = new FixedAdjuster(czdt2);
        if (chrono != chrono2) {
            try {
                czdt.plus(adjuster);
                Assert.fail("WithAdjuster should have thrown a ClassCastException, "
                        + "required: " + czdt + ", supplied: " + czdt2);
            } catch (ClassCastException cce) {
                // Expected exception; not an error
            }
        } else {
            // Same chronology,
            ChronoZonedDateTime<?> result = czdt.plus(adjuster);
            assertEquals(result, czdt2, "WithAdjuster failed to replace date time");
        }
    }
}
 
Example #8
Source File: ChronoPeriodImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ChronoPeriod minus(TemporalAmount amountToSubtract) {
    ChronoPeriodImpl amount = validateAmount(amountToSubtract);
    return new ChronoPeriodImpl(
            chrono,
            Math.subtractExact(years, amount.years),
            Math.subtractExact(months, amount.months),
            Math.subtractExact(days, amount.days));
}
 
Example #9
Source File: JobService.java    From rockscript with Apache License 2.0 5 votes vote down vote up
public void handleJobFailure(Job job, String error) {
  log.debug("Job handler "+job.getJobHandler().getClass().getSimpleName()+" error occurred: "+error);
  long errorCount = job.getErrorCount();
  TemporalAmount retryDuration = job.getNextRetryDuration();
  if (retryDuration!=null) {
    Instant nextRetryTime = Time.now().plus(retryDuration);
    job.setExecutionTime(nextRetryTime);
    engine.getEventDispatcher().dispatch(new JobFailedEvent(job.getId(), error, nextRetryTime));

  } else {
    engine.getEventDispatcher().dispatch(new JobFailedEvent(job.getId(), error));
  }
}
 
Example #10
Source File: ChronoPeriodImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ChronoPeriod plus(TemporalAmount amountToAdd) {
    ChronoPeriodImpl amount = validateAmount(amountToAdd);
    return new ChronoPeriodImpl(
            chrono,
            Math.addExact(years, amount.years),
            Math.addExact(months, amount.months),
            Math.addExact(days, amount.days));
}
 
Example #11
Source File: TCKYearMonth.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="plus_TemporalAmount")
public void test_plus_TemporalAmount(YearMonth base, TemporalAmount temporalAmount, YearMonth expectedYearMonth, Class<?> expectedEx) {
    if (expectedEx == null) {
        assertEquals(base.plus(temporalAmount), expectedYearMonth);
    } else {
        try {
            YearMonth result = base.plus(temporalAmount);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example #12
Source File: ChronoPeriodImpl.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtains an instance of {@code ChronoPeriodImpl} from a temporal amount.
 *
 * @param amount  the temporal amount to convert, not null
 * @return the period, not null
 */
private ChronoPeriodImpl validateAmount(TemporalAmount amount) {
    Objects.requireNonNull(amount, "amount");
    if (amount instanceof ChronoPeriodImpl == false) {
        throw new DateTimeException("Unable to obtain ChronoPeriod from TemporalAmount: " + amount.getClass());
    }
    ChronoPeriodImpl period = (ChronoPeriodImpl) amount;
    if (chrono.equals(period.getChronology()) == false) {
        throw new ClassCastException("Chronology mismatch, expected: " + chrono.getId() + ", actual: " + period.getChronology().getId());
    }
    return period;
}
 
Example #13
Source File: TestUtils.java    From digdag with Apache License 2.0 5 votes vote down vote up
public static void expect(TemporalAmount timeout, Callable<Boolean> condition, Duration interval)
        throws Exception
{
    Instant deadline = Instant.now().plus(timeout);
    while (Instant.now().toEpochMilli() < deadline.toEpochMilli()) {
        if (condition.call()) {
            return;
        }
        Thread.sleep(interval.toMillis());
    }

    fail("Timeout after: " + timeout);
}
 
Example #14
Source File: ChronoPeriodImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ChronoPeriod minus(TemporalAmount amountToSubtract) {
    ChronoPeriodImpl amount = validateAmount(amountToSubtract);
    return new ChronoPeriodImpl(
            chrono,
            Math.subtractExact(years, amount.years),
            Math.subtractExact(months, amount.months),
            Math.subtractExact(days, amount.days));
}
 
Example #15
Source File: ImmutableProxy.java    From reflection-util with Apache License 2.0 5 votes vote down vote up
static boolean isImmutable(Object value) {
	if (value == null) {
		return true;
	} else if (isImmutableProxy(value)) {
		return true;
	} else if (value instanceof String) {
		return true;
	} else if (value instanceof Number) {
		return true;
	} else if (value instanceof Boolean) {
		return true;
	} else if (value instanceof Character) {
		return true;
	} else if (value instanceof Temporal) {
		return true;
	} else if (value instanceof TemporalAmount) {
		return true;
	} else if (value instanceof UUID) {
		return true;
	} else if (value instanceof File) {
		return true;
	} else if (value instanceof Path) {
		return true;
	} else if (value instanceof URI) {
		return true;
	} else if (isEnumValue(value)) {
		return true;
	} else {
		return false;
	}
}
 
Example #16
Source File: PureJavaTimeFEELLib.java    From jdmn with Apache License 2.0 5 votes vote down vote up
@Override
public TemporalAmount duration(String from) {
    try {
        return this.durationLib.duration(from);
    } catch (Exception e) {
        String message = String.format("duration(%s)", from);
        logError(message, e);
        return null;
    }
}
 
Example #17
Source File: TCKYearMonth.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="plus_TemporalAmount")
public void test_plus_TemporalAmount(YearMonth base, TemporalAmount temporalAmount, YearMonth expectedYearMonth, Class<?> expectedEx) {
    if (expectedEx == null) {
        assertEquals(base.plus(temporalAmount), expectedYearMonth);
    } else {
        try {
            YearMonth result = base.plus(temporalAmount);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example #18
Source File: AbstractSpringLockConfigurationExtractorTest.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLockTimeFromAnnotationWithDurationString() throws NoSuchMethodException {
    noopResolver();
    AnnotationData annotation = getAnnotation("annotatedMethodWithDurationString");
    TemporalAmount lockAtMostFor = extractor.getLockAtMostFor(annotation);
    assertThat(lockAtMostFor).isEqualTo(Duration.of(1, SECONDS));
}
 
Example #19
Source File: Period.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtains an instance of {@code Period} from a temporal amount.
 * <p>
 * This obtains a period based on the specified amount.
 * A {@code TemporalAmount} represents an  amount of time, which may be
 * date-based or time-based, which this factory extracts to a {@code Period}.
 * <p>
 * The conversion loops around the set of units from the amount and uses
 * the {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS}
 * and {@link ChronoUnit#DAYS DAYS} units to create a period.
 * If any other units are found then an exception is thrown.
 * <p>
 * If the amount is a {@code ChronoPeriod} then it must use the ISO chronology.
 *
 * @param amount  the temporal amount to convert, not null
 * @return the equivalent period, not null
 * @throws DateTimeException if unable to convert to a {@code Period}
 * @throws ArithmeticException if the amount of years, months or days exceeds an int
 */
public static Period from(TemporalAmount amount) {
    if (amount instanceof Period) {
        return (Period) amount;
    }
    if (amount instanceof ChronoPeriod) {
        if (IsoChronology.INSTANCE.equals(((ChronoPeriod) amount).getChronology()) == false) {
            throw new DateTimeException("Period requires ISO chronology: " + amount);
        }
    }
    Objects.requireNonNull(amount, "amount");
    int years = 0;
    int months = 0;
    int days = 0;
    for (TemporalUnit unit : amount.getUnits()) {
        long unitAmount = amount.get(unit);
        if (unit == ChronoUnit.YEARS) {
            years = Math.toIntExact(unitAmount);
        } else if (unit == ChronoUnit.MONTHS) {
            months = Math.toIntExact(unitAmount);
        } else if (unit == ChronoUnit.DAYS) {
            days = Math.toIntExact(unitAmount);
        } else {
            throw new DateTimeException("Unit must be Years, Months or Days, but was " + unit);
        }
    }
    return create(years, months, days);
}
 
Example #20
Source File: TCKOffsetTime.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_plus_PlusAdjuster_null() {
    TEST_11_30_59_500_PONE.plus((TemporalAmount) null);
}
 
Example #21
Source File: BaseSchedule.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public TemporalAmount getPeriod() {
  return amount;
}
 
Example #22
Source File: TCKLocalDateTime.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_minus_TemporalAmount_null() {
    TEST_2007_07_15_12_30_40_987654321.minus((TemporalAmount) null);
}
 
Example #23
Source File: TCKOffsetTime.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_plus_PlusAdjuster_null() {
    TEST_11_30_59_500_PONE.plus((TemporalAmount) null);
}
 
Example #24
Source File: ChronoLocalDateImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public D plus(TemporalAmount amount) {
    return (D) ChronoLocalDate.super.plus(amount);
}
 
Example #25
Source File: ManLocalDateTimeExt.java    From manifold with Apache License 2.0 4 votes vote down vote up
public static LocalDateTime minus( @This LocalDateTime thiz, Time time )
{
  if( time.getDisplayUnit().isDateBased() )
  {
    // Extract the Period from the date-based time and add that
    Rational years = time.toBaseNumber() / TimeUnit.Year.getSeconds();
    int wholeYears = years.wholePart().intValue();
    Rational months = years.fractionPart() * TimeUnit.Year.getSeconds() / TimeUnit.Month.getSeconds();
    int wholeMonths = months.wholePart().intValue();
    Rational days = months.fractionPart() * TimeUnit.Month.getSeconds() / TimeUnit.Day.getSeconds();
    int wholeDays = days.wholePart().intValue();
    Period period = Period.of( wholeYears, wholeMonths, wholeDays );
    LocalDateTime newDate = thiz - period;

    // Now add the remaining fractional day part, if non-zero, as a Duration (added to the date-time's time component)
    Rational seconds = days.fractionPart() * TimeUnit.Day.getSeconds();
    if( seconds != Rational.ZERO )
    {
      long wholeSeconds = seconds.wholePart().longValue();
      long nanos = (seconds.fractionPart() * 1e+9).longValue();
      newDate = newDate - Duration.ofSeconds( wholeSeconds, nanos );
    }

    return newDate;
  }

  return thiz - (TemporalAmount)time;
}
 
Example #26
Source File: TCKYear.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test()
@UseDataProvider("data_minusValid")
public void test_minusValid(int year, TemporalAmount amount, int expected) {
    assertEquals(Year.of(year).minus(amount), Year.of(expected));
}
 
Example #27
Source File: TCKOffsetTime.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test(expected=NullPointerException.class)
public void test_minus_MinusAdjuster_null() {
    TEST_11_30_59_500_PONE.minus((TemporalAmount) null);
}
 
Example #28
Source File: TCKLocalTime.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void test_plus_TemporalAmount_zero() {
    TemporalAmount period = Period.ZERO;
    LocalTime t = TEST_12_30_40_987654321.plus(period);
    assertEquals(t, TEST_12_30_40_987654321);
}
 
Example #29
Source File: TCKLocalTime.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void test_minus_TemporalAmount_wrap() {
    TemporalAmount p = MockSimplePeriod.of(1, HOURS);
    LocalTime t = LocalTime.of(0, 30).minus(p);
    assertEquals(t, LocalTime.of(23, 30));
}
 
Example #30
Source File: TCKDuration.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void factory_from_TemporalAmount_Duration() {
    TemporalAmount amount = Duration.ofHours(3);
    assertEquals(Duration.from(amount), Duration.ofHours(3));
}