本文整理汇总了Java中java.time.temporal.ChronoUnit类的典型用法代码示例。如果您正苦于以下问题:Java ChronoUnit类的具体用法?Java ChronoUnit怎么用?Java ChronoUnit使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ChronoUnit类属于java.time.temporal包,在下文中一共展示了ChronoUnit类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: render
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
public Message render(Color color, Instant now)
{
MessageBuilder mb = new MessageBuilder();
boolean close = now.plusSeconds(6).isAfter(end);
mb.append(Constants.YAY).append(close ? " **G I V E A W A Y** " : " **GIVEAWAY** ").append(Constants.YAY);
EmbedBuilder eb = new EmbedBuilder();
if(close)
eb.setColor(Color.RED);
else if(color==null)
eb.setColor(Constants.BLURPLE);
else
eb.setColor(color);
eb.setFooter((winners==1 ? "" : winners+" Winners | ")+"Ends at",null);
eb.setTimestamp(end);
eb.setDescription("React with "+Constants.TADA+" to enter!\nTime remaining: "+FormatUtil.secondsToTime(now.until(end, ChronoUnit.SECONDS)));
if(prize!=null)
eb.setAuthor(prize, null, null);
if(close)
eb.setTitle("Last chance to enter!!!", null);
mb.setEmbed(eb.build());
return mb.build();
}
示例2: test_MinguoDate
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@SuppressWarnings("unused")
@Test(dataProvider="samples")
public void test_MinguoDate(MinguoDate minguoDate, LocalDate iso) {
MinguoDate hd = minguoDate;
ChronoLocalDateTime<MinguoDate> hdt = hd.atTime(LocalTime.NOON);
ZoneOffset zo = ZoneOffset.ofHours(1);
ChronoZonedDateTime<MinguoDate> hzdt = hdt.atZone(zo);
hdt = hdt.plus(1, ChronoUnit.YEARS);
hdt = hdt.plus(1, ChronoUnit.MONTHS);
hdt = hdt.plus(1, ChronoUnit.DAYS);
hdt = hdt.plus(1, ChronoUnit.HOURS);
hdt = hdt.plus(1, ChronoUnit.MINUTES);
hdt = hdt.plus(1, ChronoUnit.SECONDS);
hdt = hdt.plus(1, ChronoUnit.NANOS);
ChronoLocalDateTime<MinguoDate> a2 = hzdt.toLocalDateTime();
MinguoDate a3 = a2.toLocalDate();
MinguoDate a5 = hzdt.toLocalDate();
//System.out.printf(" d: %s, dt: %s; odt: %s; zodt: %s; a4: %s%n", date, hdt, hodt, hzdt, a5);
}
示例3: handleTimeoutScheduleStartMessage
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
private void handleTimeoutScheduleStartMessage(final Object obj) {
final TimeoutScheduleStartMessage msg = (TimeoutScheduleStartMessage) obj;
final SubjectState subjectState = subjectStateRepository.findOne(msg.getSsId());
final long timeout =
subjectState.getCurrentState().getTimeoutTransition().get().getTimeout().longValue();
final LocalDateTime now = LocalDateTime.now();
final LocalDateTime lastChanged = subjectState.getLastChanged();
final long alreadyPassed = ChronoUnit.MINUTES.between(lastChanged, now);
long actualTimeout = timeout - alreadyPassed;
if (actualTimeout < 0) {
actualTimeout = 0;
}
LOG.info("Start [{}] min. timeout for [{}]", actualTimeout, subjectState);
scheduler = actorSystem.scheduler()
.scheduleOnce(Duration.create(actualTimeout, TimeUnit.MINUTES), () -> {
getContext().parent().tell(new TimeoutExecuteMessage(subjectState.getSsId()), getSelf());
getContext().stop(getSelf());
}, actorSystem.dispatcher());
}
示例4: read
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Override
public QuoteBySourceAmountResponse read(CodecContext context, InputStream inputStream)
throws IOException {
Objects.requireNonNull(context);
Objects.requireNonNull(inputStream);
/* read the destination amount, which is a uint64 */
final BigInteger destinationAmount = context.read(OerUint64.class, inputStream).getValue();
/* read the source hold duration which is a unit32 */
long sourceHoldDuration = context.read(OerUint32.class, inputStream).getValue();
return QuoteBySourceAmountResponse.Builder.builder()
.destinationAmount(destinationAmount)
.sourceHoldDuration(Duration.of(sourceHoldDuration, ChronoUnit.MILLIS)).build();
}
示例5: assertThatResetKeyMustNotBeOlderThan24Hours
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Test
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
UserLogin userLogin = new UserLogin();
userLogin.setTypeKey(UserLoginType.EMAIL.getValue());
userLogin.setLogin("[email protected]");
User user = new User();
user.setUserKey("test");
user.setPassword(RandomStringUtils.random(60));
user.getLogins().add(userLogin);
userLogin.setUser(user);
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.save(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser.isPresent()).isFalse();
userRepository.delete(user);
}
示例6: test
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Test
public void test(){
Flux.just("Ben", "Michael", "Mark")
.doOnNext(v -> {
if (new Random().nextInt(10) + 1 == 5) {
throw new RuntimeException("Boo!");
}
})
.doOnSubscribe(subscription ->
{
System.out.println(subscription);
})
.retryWhen(throwableFlux -> Flux.range(1, 5)
.flatMap(i -> {
System.out.println(i);
return Flux.just(i)
.delay(Duration.of(i, ChronoUnit.SECONDS));
}))
.subscribe(System.out::println);
}
示例7: plus
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public D plus(long amountToAdd, TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
ChronoUnit f = (ChronoUnit) unit;
switch (f) {
case DAYS: return plusDays(amountToAdd);
case WEEKS: return plusDays(Math.multiplyExact(amountToAdd, 7));
case MONTHS: return plusMonths(amountToAdd);
case YEARS: return plusYears(amountToAdd);
case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return (D) ChronoLocalDate.super.plus(amountToAdd, unit);
}
示例8: listTransports
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Override
public Page<TransportListViewDTO> listTransports(Pageable pageable) {
return transportRepository.findAll(pageable).map(transport -> {
TransportListViewDTO listViewDTO = new TransportListViewDTO();
//Map transport to dto
listViewDTO.setId(transport.getId());
listViewDTO.setCargoName(transport.getCargo().getName());
listViewDTO.setCityFrom(transport.getPlaceOfLoad().getCity());
listViewDTO.setCityTo(transport.getPlaceOfUnload().getCity());
listViewDTO.setDescription(transport.getCargo().getDescription());
listViewDTO.setOwner(transport.getOwner().getUserName());
if (transport.getBids().size() > 0) {
listViewDTO.setCurrentPrice(transport.getBids().stream().mapToInt(b -> b.getAmount()).min().getAsInt());
listViewDTO.setLowestBidder(transport.getBids().stream().min(Comparator.comparing(Bid::getAmount)).get().getBidder().getUserName());
} else {
listViewDTO.setCurrentPrice(transport.getStartingPrice());
listViewDTO.setLowestBidder("");
}
listViewDTO.setDaysRemaining(ChronoUnit.DAYS.between(LocalDate.now(), transport.getTimeOfLoad()));
return listViewDTO;
});
}
示例9: run
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Override
public void run() {
LOGGER.info("Started ZMQ pusher");
pull.connect("tcp://127.0.0.1:"+ port);
while (!Thread.interrupted() || stopped.get()) {
String m = null;
try {
m = pull.recvStr();
InputHandler.handleMessage(m);
} catch (ZMQException ex) {
LOGGER.error("ZMQ error in KV7/8 processing", ex);
} catch (Exception e) {
LOGGER.error("Error in KV7/8 processing", e);
metrics.increaseBucketValue("kv78turbo.messages.errors", ChronoUnit.HOURS);
if (m != null) {
LOGGER.debug("Got message {}", m);
}
}
}
LOGGER.debug("Processing task is interrupted");
disconnect();
}
示例10: test_isSupported_TemporalUnit
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Test
public void test_isSupported_TemporalUnit() {
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported((TemporalUnit) null), false);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.NANOS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MICROS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MILLIS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.SECONDS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MINUTES), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.HOURS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.HALF_DAYS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.DAYS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.WEEKS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MONTHS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.YEARS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.DECADES), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.CENTURIES), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MILLENNIA), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.ERAS), true);
assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.FOREVER), false);
}
示例11: borrowBook
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@FXML
private void borrowBook(ActionEvent event) {
if(!borrowed.isBookBorrowedAlready(Main.getId(), this.bookId)) {
LocalDate today = LocalDate.now();
LocalDate next2Week = today.plus(2, ChronoUnit.WEEKS);
borrowed.addNewBorrowedBook(Main.getId(), this.bookId, today.toString(), next2Week.toString());
book.updateBookQuantity(this.bookId, -1);
quantity.setText(Integer.toString(bookDetails.getQuantity() - 1));
warning.setTextFill(Color.web("#00FF00"));
warning.setText("Book successfully borrowed!");
this.isBorrowOrRequestAllowed();
} else {
warning.setTextFill(Color.web("#FF0000"));
warning.setText("Book borrowed already!");
}
}
示例12: isExpired
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Override
public boolean isExpired(final TicketState ticketState) {
final ZonedDateTime currentSystemTime = ZonedDateTime.now(ZoneOffset.UTC);
final ZonedDateTime creationTime = ticketState.getCreationTime();
final ZonedDateTime lastTimeUsed = ticketState.getLastTimeUsed();
// Ticket has been used, check maxTimeToLive (hard window)
ZonedDateTime expirationTime = creationTime.plus(this.maxTimeToLiveInSeconds, ChronoUnit.SECONDS);
if (currentSystemTime.isAfter(expirationTime)) {
LOGGER.debug("Ticket is expired because the time since creation is greater than maxTimeToLiveInSeconds");
return true;
}
expirationTime = lastTimeUsed.plus(this.timeToKillInSeconds, ChronoUnit.SECONDS);
if (currentSystemTime.isAfter(expirationTime)) {
LOGGER.debug("Ticket is expired because the time since last use is greater than timeToKillInSeconds");
return true;
}
return false;
}
示例13: testRangeOfLocalDates
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Test(dataProvider = "localDateRanges")
public void testRangeOfLocalDates(LocalDate start, LocalDate end, Period step, boolean parallel) {
final Range<LocalDate> range = Range.of(start, end, step);
final Array<LocalDate> array = range.toArray(parallel);
final boolean ascend = start.isBefore(end);
final int expectedLength = (int)Math.ceil(Math.abs((double)ChronoUnit.DAYS.between(start, end)) / (double)step.getDays());
Assert.assertEquals(array.length(), expectedLength);
Assert.assertEquals(array.typeCode(), ArrayType.LOCAL_DATE);
Assert.assertTrue(!array.style().isSparse());
Assert.assertEquals(range.start(), start, "The range start");
Assert.assertEquals(range.end(), end, "The range end");
LocalDate expected = null;
for (int i=0; i<array.length(); ++i) {
final LocalDate actual = array.getValue(i);
expected = expected == null ? start : ascend ? expected.plus(step) : expected.minus(step);
Assert.assertEquals(actual, expected, "Value matches at " + i);
Assert.assertTrue(ascend ? actual.compareTo(start) >=0 && actual.isBefore(end) : actual.compareTo(start) <= 0 && actual.isAfter(end), "Value in bounds at " + i);
}
}
示例14: chronoRangeTest3
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Test
public void chronoRangeTest3() {
ChronoSeries chronoSeries = ChronoSeries.fromFrequency(1, ChronoUnit.SECONDS,
Instant.parse("2017-07-30T14:08:20Z"), Instant.parse("2017-07-30T14:18:24Z"));
ISeq<ChronoGene> genes = ISeq.of(
new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.MINUTES), 0, 14)),
new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.MINUTES), 0, 18))
);
ChronoRange chronoRange = ChronoRange.getChronoRange(chronoSeries, genes);
assertTrue(chronoRange.getTimestampRanges().size() == 2);
assertArrayEquals("Invalid ChronoRange", new Instant[]{
Instant.parse("2017-07-30T14:14:00Z"),
Instant.parse("2017-07-30T14:15:00Z"),
}, chronoRange.getTimestampRanges().get(0));
assertArrayEquals("Invalid ChronoRange", new Instant[]{
Instant.parse("2017-07-30T14:18:00Z"),
Instant.parse("2017-07-30T14:18:24Z"),
}, chronoRange.getTimestampRanges().get(1));
assertTrue(chronoRange.getRangeDuration().getSeconds() == (60 + 24));
}
示例15: assertThatResetKeyMustNotBeOlderThan24Hours
import java.time.temporal.ChronoUnit; //导入依赖的package包/类
@Test
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "[email protected]", "http://placehold.it/50x50", "en-US");
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.save(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser.isPresent()).isFalse();
userRepository.delete(user);
}