Java 类java.time.temporal.ChronoUnit 实例源码

项目:IPPR2016    文件:TimeoutScheduleActor.java   
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());
}
项目:quilt    文件:QuoteBySourceAmountResponseOerCodec.java   
@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();
}
项目:Spring-5.0-Cookbook    文件:TestEmployeeNativeStreamService.java   
@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);
}
项目:jdk8u-jdk    文件:ChronoLocalDateImpl.java   
@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);
}
项目:RFTBackend    文件:TransportServiceImpl.java   
@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;
    });
}
项目:jdk8u-jdk    文件:TCKMinguoChronology.java   
@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);
}
项目:displaydirect    文件:Kv78ProcessTask.java   
@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();
}
项目:GiveawayBot    文件:Giveaway.java   
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();
}
项目:jdk8u-jdk    文件:TCKOffsetDateTime.java   
@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);
}
项目:IP1    文件:SearchDetailsController.java   
@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!");
    }
}
项目:openjdk-jdk10    文件:TCKMinguoChronology.java   
@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);
}
项目:cas-5.1.0    文件:TicketGrantingTicketExpirationPolicy.java   
@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;
}
项目:morpheus-core    文件:RangeBasicTests.java   
@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);
    }
}
项目:Chronetic    文件:ChronoRangeTest.java   
@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));
}
项目:cas-5.1.0    文件:MultiTimeUseOrTimeoutExpirationPolicy.java   
@Override
public boolean isExpired(final TicketState ticketState) {
    if (ticketState == null) {
        LOGGER.debug("Ticket state is null for [{}]", this.getClass().getSimpleName());
        return true;
    }
    final long countUses = ticketState.getCountOfUses();
    if (countUses >= this.numberOfUses) {
        LOGGER.debug("Ticket usage count [{}] is greater than or equal to [{}]", countUses, this.numberOfUses);
        return true;
    }

    final ZonedDateTime systemTime = ZonedDateTime.now(ZoneOffset.UTC);
    final ZonedDateTime lastTimeUsed = ticketState.getLastTimeUsed();
    final ZonedDateTime expirationTime = lastTimeUsed.plus(this.timeToKillInSeconds, ChronoUnit.SECONDS);

    if (systemTime.isAfter(expirationTime)) {
        LOGGER.debug("Ticket has expired because the difference between current time [{}] "
                        + "and ticket time [{}] is greater than or equal to [{}]", systemTime, lastTimeUsed,
                this.timeToKillInSeconds);
        return true;
    }
    return false;
}
项目:InfoSys-1D    文件:WeekCalendarServiceImpl.java   
private List<List<String>> createProfCalMatrix(String profAlias, LocalDate startDateOfSchoolWeek) {
    List<BookingSlot> slotList = slotService.getSlotsByProfAndSWeek(profAlias, startDateOfSchoolWeek);
    List<List<String>> output = new ArrayList<>();
    List<String> temp;

    for (int i = 0; i < WEEK_CAL_ROW; i++) {
        LocalTime timePart = ROW_TO_TIME.get(i);
        String timeRange = timeRangeFormat(timePart);

        temp = new ArrayList<>();
        temp.add(timeRange);

        for (int j = 0; j < WEEK_CAL_COL; j++) {
            LocalDate datePart = startDateOfSchoolWeek.plus(j, ChronoUnit.DAYS);
            LocalDateTime dateTime = LocalDateTime.of(datePart, timePart);

            temp.add(createProfCalString(dateTime, slotList));
        }

        output.add(temp);
    }

    return output;
}
项目:Chronetic    文件:ChronoRangeTest.java   
@Test
public void chronoRangeCompareTest3() {
    ChronoSeries chronoSeries = ChronoSeries.of(
            Instant.parse("2011-11-04T08:48:11Z"),
            Instant.parse("2012-11-02T09:23:16Z"),
            Instant.parse("2013-11-01T09:51:49Z"),
            Instant.parse("2014-11-07T08:43:00Z"),
            Instant.parse("2015-11-06T08:22:25Z")
    );
    ISeq<ChronoGene> genes = ISeq.of(
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.HOURS), 0, 0))
    );
    ChronoRange chronoRange = ChronoRange.getChronoRange(chronoSeries, genes);

    genes = ISeq.of(
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.HOURS), 0, 8))
    );
    ChronoRange chronoRange2 = ChronoRange.getChronoRange(chronoSeries, genes);

    assertTrue(chronoRange.isSameChronoRange(chronoRange2));
}
项目:Chronetic    文件:ChronoRangeTest.java   
@Test
public void chronoRangeCompareTest9() {
    ChronoSeries chronoSeries = ChronoSeries.of(
            Instant.parse("2011-11-04T08:48:11Z"),
            Instant.parse("2012-11-02T09:23:16Z"),
            Instant.parse("2013-11-01T09:51:49Z"),
            Instant.parse("2014-11-07T08:43:00Z"),
            Instant.parse("2015-11-06T08:22:25Z")
    );
    ISeq<ChronoGene> genes = ISeq.of(
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.WEEKS), 0, 1))
    );
    ChronoRange chronoRange = ChronoRange.getChronoRange(chronoSeries, genes);

    genes = ISeq.of(
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.MONTHS), 0, 11)),
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.MINUTES), 0, 43))
    );
    ChronoRange chronoRange2 = ChronoRange.getChronoRange(chronoSeries, genes);

    assertTrue(chronoRange.isSameChronoRange(chronoRange2));
}
项目:pugtsdb    文件:Temporals.java   
public static ZonedDateTime truncate(ZonedDateTime time, ChronoUnit unit) {
    switch (unit) {
        case NANOS:
        case MICROS:
        case MILLIS:
        case SECONDS:
        case MINUTES:
        case HOURS:
        case HALF_DAYS:
        case DAYS:
            return time.truncatedTo(unit);
        case MONTHS:
            return time.truncatedTo(DAYS).withDayOfMonth(1);
        case YEARS:
            return time.truncatedTo(DAYS).withDayOfYear(1);
        default:
            throw new UnsupportedTemporalTypeException("Invalid unit for truncation: " + unit);
    }
}
项目:grittier_ext    文件:Tags.java   
public static void createTags(Node post, HashMap<String, Object>  input, LocalDateTime dateTime, GraphDatabaseService db) {
    Matcher mat = hashtagPattern.matcher(((String)input.get("status")).toLowerCase());
    for (Relationship r1 : post.getRelationships(Direction.OUTGOING, RelationshipType.withName("TAGGED_ON_" +
            dateTime.format(dateFormatter)))) {
        r1.delete();
    }
    Set<Node> tagged = new HashSet<>();
    while (mat.find()) {
        String tag = mat.group(1);
        Node hashtag = db.findNode(Labels.Tag, NAME, tag);
        if (hashtag == null) {
            hashtag = db.createNode(Labels.Tag);
            hashtag.setProperty(NAME, tag);
            hashtag.setProperty(TIME, dateTime.truncatedTo(ChronoUnit.DAYS).toEpochSecond(ZoneOffset.UTC));
        }
        if (!tagged.contains(hashtag)) {
            post.createRelationshipTo(hashtag, RelationshipType.withName("TAGGED_ON_" +
                    dateTime.format(dateFormatter)));
            tagged.add(hashtag);
        }
    }
}
项目:calendar-component    文件:Calendar.java   
@Override
public void rangeSelect(SelectionRange selectionRange) {

    if (!isClientChangeAllowed()) {
        return;
    }

    // MounthSelection
    if (selectionRange.s != null && selectionRange.e != null) {

        fireRangeSelect(
                ZonedDateTime.of(
                        selectionRange.s.y,
                        selectionRange.s.m,
                        selectionRange.s.d,
                        0,0,0,0, getZoneId()),
                ZonedDateTime.of(
                        selectionRange.e.y,
                        selectionRange.e.m,
                        selectionRange.e.d,
                        23, 59, 59, 999999, getZoneId()));

    } else if (selectionRange.s != null) {

        ZonedDateTime dateTime = ZonedDateTime.of(
                selectionRange.s.y,
                selectionRange.s.m,
                selectionRange.s.d,
                0,0,0,0, getZoneId());

        ZonedDateTime start = ZonedDateTime.from(dateTime.plus(selectionRange.sMin, ChronoUnit.MINUTES));
        ZonedDateTime end   = ZonedDateTime.from(dateTime.plus(selectionRange.eMin, ChronoUnit.MINUTES));

        fireRangeSelect(start, end);

    }
}
项目:jdk8u-jdk    文件:TCKLocalDateTime.java   
@DataProvider(name="query")
Object[][] data_query() {
    return new Object[][] {
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.chronology(), IsoChronology.INSTANCE},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.zoneId(), null},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.precision(), ChronoUnit.NANOS},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.zone(), null},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.offset(), null},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.localDate(), LocalDate.of(2007, 7, 15)},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.localTime(), LocalTime.of(12, 30, 40, 987654321)},
    };
}
项目:Saber-Bot    文件:Logging.java   
/**
 * used logging minor (possibly expected) errors (level 2)
 * @param caller the java class from which the command is called
 * @param msg the message to log
 */
public static void warn(Class caller, String msg)
{
    if(Main.getBotSettingsManager().getLogLevel() < 2) return;

    String now = LocalTime.now().truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_LOCAL_TIME);
    String content = "[" + now + "] " +
            ANSI_RED + "[Warn]" + ANSI_RESET + " " +
            ANSI_YELLOW_BACKGROUND + ANSI_BLACK +
            "[" + caller.getSimpleName() + "]" +
            ANSI_RESET + " " + ANSI_RED + msg +
            ANSI_RESET;

    System.out.println(content);
}
项目:learn-java8    文件:DateTests.java   
@Test
public void testSpecificDate() {
      LocalDate Christmas = LocalDate.of(2014, Month.DECEMBER, 25);
      System.out.println("Christmas Date: " + Christmas);

      LocalDate newYearsDay = Christmas.plus(1, ChronoUnit.WEEKS);
      System.out.println("New Years Eve: " + newYearsDay);

      assertEquals(DayOfWeek.THURSDAY, newYearsDay.getDayOfWeek());
      assertEquals(1, newYearsDay.getDayOfMonth());
      assertEquals(1, newYearsDay.getMonthValue());
      assertEquals(2015, newYearsDay.getYear());
}
项目:openjdk-jdk10    文件:TestIsoWeekFields.java   
@Test(dataProvider = "fields")
public void test_WBY_basics(TemporalField weekField, TemporalField yearField) {
    assertEquals(yearField.isDateBased(), true);
    assertEquals(yearField.isTimeBased(), false);
    assertEquals(yearField.getBaseUnit(), IsoFields.WEEK_BASED_YEARS);
    assertEquals(yearField.getRangeUnit(), ChronoUnit.FOREVER);
}
项目:Shadbot    文件:HangmanManager.java   
public HangmanManager(AbstractCommand cmd, String prefix, IChannel channel, IUser author, Difficulty difficulty) {
    super(cmd, prefix, channel, author);
    this.rateLimiter = new RateLimiter(2, 2, ChronoUnit.SECONDS);
    this.message = new UpdateableMessage(channel);
    this.word = HangmanCmd.getWord(difficulty);
    this.charsTested = new ArrayList<>();
    this.failsCount = 0;
}
项目:jdk8u-jdk    文件:TCKLocalDate.java   
@DataProvider(name="query")
Object[][] data_query() {
    return new Object[][] {
            {TEST_2007_07_15, TemporalQueries.chronology(), IsoChronology.INSTANCE},
            {TEST_2007_07_15, TemporalQueries.zoneId(), null},
            {TEST_2007_07_15, TemporalQueries.precision(), ChronoUnit.DAYS},
            {TEST_2007_07_15, TemporalQueries.zone(), null},
            {TEST_2007_07_15, TemporalQueries.offset(), null},
            {TEST_2007_07_15, TemporalQueries.localDate(), TEST_2007_07_15},
            {TEST_2007_07_15, TemporalQueries.localTime(), null},
    };
}
项目:Saber-Bot    文件:ScheduleEntry.java   
/**
 * handles when an event ends
 */
public void end()
{
    Message msg = this.getMessageObject();
    if(msg == null) return;

    if(!this.quietEnd)
    {
        // dont send end announcement if 15 minutes late
        if(this.entryEnd.isAfter(ZonedDateTime.now().minusMinutes(15)))
        {
            // send the end announcement
            String endMsg = ParsingUtilities.parseMessageFormat(Main.getScheduleManager().getEndAnnounceFormat(this.chanId), this, true);
            String identifier = Main.getScheduleManager().getEndAnnounceChan(this.chanId);
            if(identifier != null)
            {
                announcementHelper(msg, endMsg, identifier);
                Logging.event(this.getClass(), "Ended event \"" + this.getTitle() + "\" [" + this.entryId + "] scheduled for " +
                        this.getEnd().withZoneSameInstant(ZoneId.systemDefault())
                                .truncatedTo(ChronoUnit.MINUTES).toLocalTime().toString());
            }
        }
    }
    else
    {
        Logging.warn(this.getClass(), "Late event end: "+this.entryTitle+" ["+this.entryId+"] "+this.entryEnd);
    }

    this.repeat();
}
项目:jdk8u-jdk    文件:TCKYearMonth.java   
@DataProvider(name="plus_long_TemporalUnit")
Object[][] data_plus_long_TemporalUnit() {
    return new Object[][] {
        {YearMonth.of(1, 10), 1, ChronoUnit.YEARS, YearMonth.of(2, 10), null},
        {YearMonth.of(1, 10), -12, ChronoUnit.YEARS, YearMonth.of(-11, 10), null},
        {YearMonth.of(1, 10), 0, ChronoUnit.YEARS, YearMonth.of(1, 10), null},
        {YearMonth.of(999999999, 12), 0, ChronoUnit.YEARS, YearMonth.of(999999999, 12), null},
        {YearMonth.of(-999999999, 1), 0, ChronoUnit.YEARS, YearMonth.of(-999999999, 1), null},
        {YearMonth.of(0, 1), -999999999, ChronoUnit.YEARS, YearMonth.of(-999999999, 1), null},
        {YearMonth.of(0, 12), 999999999, ChronoUnit.YEARS, YearMonth.of(999999999, 12), null},

        {YearMonth.of(1, 10), 1, ChronoUnit.MONTHS, YearMonth.of(1, 11), null},
        {YearMonth.of(1, 10), -12, ChronoUnit.MONTHS, YearMonth.of(0, 10), null},
        {YearMonth.of(1, 10), 0, ChronoUnit.MONTHS, YearMonth.of(1, 10), null},
        {YearMonth.of(999999999, 12), 0, ChronoUnit.MONTHS, YearMonth.of(999999999, 12), null},
        {YearMonth.of(-999999999, 1), 0, ChronoUnit.MONTHS, YearMonth.of(-999999999, 1), null},
        {YearMonth.of(-999999999, 2), -1, ChronoUnit.MONTHS, YearMonth.of(-999999999, 1), null},
        {YearMonth.of(999999999, 3), 9, ChronoUnit.MONTHS, YearMonth.of(999999999, 12), null},

        {YearMonth.of(-1, 10), 1, ChronoUnit.ERAS, YearMonth.of(2, 10), null},
        {YearMonth.of(5, 10), 1, ChronoUnit.CENTURIES, YearMonth.of(105, 10), null},
        {YearMonth.of(5, 10), 1, ChronoUnit.DECADES, YearMonth.of(15, 10), null},

        {YearMonth.of(999999999, 12), 1, ChronoUnit.MONTHS, null, DateTimeException.class},
        {YearMonth.of(-999999999, 1), -1, ChronoUnit.MONTHS, null, DateTimeException.class},

        {YearMonth.of(1, 1), 0, ChronoUnit.DAYS, null, DateTimeException.class},
        {YearMonth.of(1, 1), 0, ChronoUnit.WEEKS, null, DateTimeException.class},
    };
}
项目:Hydrograph    文件:DateFunctions.java   
/**
 * Returns an integer which hold difference of years between two dates
 *
 * @param fromDate the date from which the difference is to be calculated
 * @param toDate   the date to which the difference is to be calculated
 * @return difference of years between {@code fromDate} and {@code toDate}
 * if either of {@code fromDate} or {@code toDate} are null return null
 */
public static Integer getYearDifference(Date fromDate, Date toDate) {

    if (fromDate == null || toDate == null)
        return null;
    Date localFromDate = new Date(fromDate.getTime());
    Date localToDate = new Date(toDate.getTime());

    LocalDateTime firstDate = LocalDateTime.ofInstant(localFromDate.toInstant(), ZoneId.systemDefault());
    LocalDateTime secondDate = LocalDateTime.ofInstant(localToDate.toInstant(), ZoneId.systemDefault());
    long years = Math.abs(ChronoUnit.YEARS.between(firstDate, secondDate));
    return (int) (long) years;
}
项目:vind    文件:FullTextEntry.java   
public FullTextEntry(Application application, String source, FulltextSearch search, SearchResult result, ZonedDateTime start, ZonedDateTime end, Session session) {
    this.application = application;
    this.session = session;
    this.timeStamp = start;
    this.request = new FullTextRequest(search,source);
    this.response = new Response(result.getNumOfResults(), start.until(end, ChronoUnit.MILLIS));
    this.sorting = search.getSorting().toString();
    this.paging = new Paging(search.getResultSet());
}
项目:openjdk-jdk10    文件:TestUmmAlQuraChronology.java   
@Test (dataProvider="monthDays")
public void test_valueRange_monthDays(int year, int month, int maxlength) {
    ChronoLocalDate date = HijrahChronology.INSTANCE.date(year, month, 1);
    ValueRange range = null;
    for (int i=1; i<=12; i++) {
        range = date.range(ChronoField.DAY_OF_MONTH);
        date = date.plus(1, ChronoUnit.MONTHS);
        assertEquals(range.getMaximum(), month, maxlength);
    }
}
项目:Chronetic    文件:ChronoScale.java   
/**
 * Returns the parent ChronoUnit for the given ChronoUnit.
 *
 * @param chronoUnit desired ChronoUnit
 * @return parent ChronoUnit of the given ChronoUnit
 */
@NotNull
public static ChronoUnit getParentChronoUnit(@NotNull ChronoUnit chronoUnit) {
    switch (requireNonNull(chronoUnit)) {
        case NANOS:
            return ChronoUnit.SECONDS;
        case MICROS:
            return ChronoUnit.SECONDS;
        case MILLIS:
            return ChronoUnit.SECONDS;
        case SECONDS:
            return ChronoUnit.MINUTES;
        case MINUTES:
            return ChronoUnit.HOURS;
        case HOURS:
            return ChronoUnit.DAYS;
        case DAYS:
            return ChronoUnit.WEEKS;
        case WEEKS:
            return ChronoUnit.MONTHS;
        case MONTHS:
            return ChronoUnit.YEARS;
        case YEARS:
            return ChronoUnit.DECADES;
        case DECADES:
            return ChronoUnit.CENTURIES;
        case CENTURIES:
            return ChronoUnit.ERAS;
        default:
            throw new UnsupportedOperationException("Unsupported chrono unit: " + chronoUnit);
    }
}
项目:TorgCRM-Server    文件:UserServiceIntTest.java   
@Test
@Transactional
public void assertThatResetKeyMustBeValid() {
    Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
    user.setActivated(true);
    user.setResetDate(daysAgo);
    user.setResetKey("1234");
    userRepository.saveAndFlush(user);

    Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
    assertThat(maybeUser).isNotPresent();
    userRepository.delete(user);
}
项目:spring-io    文件:UserServiceIntTest.java   
@Test
public void testFindNotActivatedUsersByCreationDateBefore() {
    userService.removeNotActivatedUsers();
    Instant now = Instant.now();
    List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
    assertThat(users).isEmpty();
}
项目:codemotion-2017-taller-de-jhipster    文件:UserServiceIntTest.java   
@Test
@Transactional
public void testFindNotActivatedUsersByCreationDateBefore() {
    Instant now = Instant.now();
    user.setActivated(false);
    User dbUser = userRepository.saveAndFlush(user);
    dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
    userRepository.saveAndFlush(user);
    List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
    assertThat(users).isNotEmpty();
    userService.removeNotActivatedUsers();
    users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
    assertThat(users).isEmpty();
}
项目:Chronetic    文件:ChronoDescriptor.java   
@NotNull
private String everyChronoUnit(@NotNull ChronoUnit chronoUnit) {
    String singular = singularChronoUnit(requireNonNull(chronoUnit));
    switch (singular) {
        case "nanosecond":
            return "every nanosecond";
        case "microsecond":
            return "every microsecond";
        case "millisecond":
            return "every millisecond";
        case "second":
            return "every second";
        case "minute":
            return "every minute";
        case "hour":
            return "every hour";
        case "day":
            return "every day";
        case "week":
            return "every week";
        case "month":
            return "every month";
        case "year":
            return "every year";
        default:
            throw new RuntimeException("bad");
    }
}