當前位置: 首頁>>代碼示例>>Java>>正文


Java ChronoUnit類代碼示例

本文整理匯總了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();
}
 
開發者ID:jagrosh,項目名稱:GiveawayBot,代碼行數:23,代碼來源:Giveaway.java

示例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);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:20,代碼來源:TCKMinguoChronology.java

示例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());
}
 
開發者ID:stefanstaniAIM,項目名稱:IPPR2016,代碼行數:23,代碼來源:TimeoutScheduleActor.java

示例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();
}
 
開發者ID:hyperledger,項目名稱:quilt,代碼行數:18,代碼來源:QuoteBySourceAmountResponseOerCodec.java

示例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);
}
 
開發者ID:xm-online,項目名稱:xm-uaa,代碼行數:27,代碼來源:UserServiceIntTest.java

示例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);
}
 
開發者ID:PacktPublishing,項目名稱:Spring-5.0-Cookbook,代碼行數:21,代碼來源:TestEmployeeNativeStreamService.java

示例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);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:20,代碼來源:ChronoLocalDateImpl.java

示例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;
    });
}
 
開發者ID:RFTDevGroup,項目名稱:RFTBackend,代碼行數:25,代碼來源:TransportServiceImpl.java

示例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();
}
 
開發者ID:CROW-NDOV,項目名稱:displaydirect,代碼行數:26,代碼來源:Kv78ProcessTask.java

示例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);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:21,代碼來源:TCKOffsetDateTime.java

示例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!");
    }
}
 
開發者ID:bartoszgajda55,項目名稱:IP1,代碼行數:20,代碼來源:SearchDetailsController.java

示例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;
}
 
開發者ID:mrluo735,項目名稱:cas-5.1.0,代碼行數:22,代碼來源:TicketGrantingTicketExpirationPolicy.java

示例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);
    }
}
 
開發者ID:zavtech,項目名稱:morpheus-core,代碼行數:20,代碼來源:RangeBasicTests.java

示例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));
}
 
開發者ID:BFergerson,項目名稱:Chronetic,代碼行數:22,代碼來源:ChronoRangeTest.java

示例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);
}
 
開發者ID:deepu105,項目名稱:spring-io,代碼行數:19,代碼來源:UserServiceIntTest.java


注:本文中的java.time.temporal.ChronoUnit類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。