类java.time.temporal.TemporalAmount源码实例Demo

下面列出了怎么用java.time.temporal.TemporalAmount的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: openjdk-jdk9   文件: TCKChronoZonedDateTime.java
@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");
        }
    }
}
 
源代码2 项目: phoebus   文件: TimeParserTest.java
/**
 * 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());
}
 
源代码3 项目: openjdk-jdk8u   文件: TCKChronoZonedDateTime.java
@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");
        }
    }
}
 
源代码4 项目: dremio-oss   文件: ScheduleUtils.java
/**
 * 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);
    }
  };
}
 
源代码5 项目: TencentKona-8   文件: TCKChronoZonedDateTime.java
@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");
        }
    }
}
 
源代码6 项目: jdk8u_jdk   文件: TCKChronoLocalDate.java
@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");
        }
    }
}
 
源代码7 项目: openjdk-8   文件: TCKChronoZonedDateTime.java
@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");
        }
    }
}
 
源代码8 项目: hottub   文件: TCKYearMonth.java
@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));
        }
    }
}
 
源代码9 项目: jdmn   文件: PureJavaTimeFEELLib.java
@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;
    }
}
 
源代码10 项目: openjdk-jdk8u-backup   文件: ChronoPeriodImpl.java
@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));
}
 
源代码11 项目: digdag   文件: TestUtils.java
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);
}
 
源代码12 项目: jdk8u-jdk   文件: ChronoPeriodImpl.java
@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));
}
 
源代码13 项目: jdk8u60   文件: ChronoPeriodImpl.java
@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));
}
 
@Test
public void shouldLockTimeFromAnnotationWithDurationString() throws NoSuchMethodException {
    noopResolver();
    AnnotationData annotation = getAnnotation("annotatedMethodWithDurationString");
    TemporalAmount lockAtMostFor = extractor.getLockAtMostFor(annotation);
    assertThat(lockAtMostFor).isEqualTo(Duration.of(1, SECONDS));
}
 
源代码15 项目: reflection-util   文件: ImmutableProxy.java
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;
	}
}
 
源代码16 项目: jdk8u_jdk   文件: ChronoPeriodImpl.java
/**
 * 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;
}
 
源代码17 项目: rockscript   文件: JobService.java
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));
  }
}
 
源代码18 项目: openjdk-8-source   文件: TCKYearMonth.java
@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));
        }
    }
}
 
源代码19 项目: manifold   文件: ManLocalDateTimeExt.java
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;
}
 
源代码20 项目: dragonwell8_jdk   文件: Period.java
/**
 * 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);
}
 
源代码21 项目: openjdk-8-source   文件: TCKOffsetTime.java
@Test(expectedExceptions=NullPointerException.class)
public void test_plus_PlusAdjuster_null() {
    TEST_11_30_59_500_PONE.plus((TemporalAmount) null);
}
 
源代码22 项目: openjdk-jdk9   文件: TCKLocalTime.java
@Test(expectedExceptions=DateTimeException.class)
public void test_plus_TemporalAmount_dateNotAllowed() {
    TemporalAmount period = MockSimplePeriod.of(7, ChronoUnit.MONTHS);
    TEST_12_30_40_987654321.plus(period);
}
 
源代码23 项目: garmadon   文件: GarmadonReader.java
public Builder recurring(Runnable action, TemporalAmount period) {
    recurrentActions.add(new RecurrentAction(action, period));
    return this;
}
 
源代码24 项目: dremio-oss   文件: BaseSchedule.java
@Override
public TemporalAmount getPeriod() {
  return amount;
}
 
源代码25 项目: j2objc   文件: TCKYear.java
@Test()
@UseDataProvider("data_minusValid")
public void test_minusValid(int year, TemporalAmount amount, int expected) {
    assertEquals(Year.of(year).minus(amount), Year.of(expected));
}
 
源代码26 项目: j2objc   文件: TCKOffsetTime.java
@Test(expected=NullPointerException.class)
public void test_minus_MinusAdjuster_null() {
    TEST_11_30_59_500_PONE.minus((TemporalAmount) null);
}
 
源代码27 项目: hottub   文件: TCKOffsetTime.java
@Test(expectedExceptions=NullPointerException.class)
public void test_plus_PlusAdjuster_null() {
    TEST_11_30_59_500_PONE.plus((TemporalAmount) null);
}
 
源代码28 项目: jdk8u60   文件: TCKDuration.java
@Test
public void factory_from_TemporalAmount_Duration() {
    TemporalAmount amount = Duration.ofHours(3);
    assertEquals(Duration.from(amount), Duration.ofHours(3));
}
 
源代码29 项目: openjdk-jdk8u-backup   文件: TCKLocalTime.java
@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));
}
 
源代码30 项目: openjdk-jdk9   文件: TCKLocalTime.java
@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);
}
 
 类所在包
 同包方法