Java Code Examples for java.time.LocalDateTime#plusMinutes()

The following examples show how to use java.time.LocalDateTime#plusMinutes() . These examples are extracted from open source projects. 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
@Test
public void test_plusMinutes_one() {
    LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
    LocalDate d = t.toLocalDate();

    int hour = 0;
    int min = 0;

    for (int i = 0; i < 70; i++) {
        t = t.plusMinutes(1);
        min++;
        if (min == 60) {
            hour++;
            min = 0;
        }

        assertEquals(t.toLocalDate(), d);
        assertEquals(t.getHour(), hour);
        assertEquals(t.getMinute(), min);
    }
}
 
Example 2
@Test
public void test_plusMinutes_one() {
    LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
    LocalDate d = t.toLocalDate();

    int hour = 0;
    int min = 0;

    for (int i = 0; i < 70; i++) {
        t = t.plusMinutes(1);
        min++;
        if (min == 60) {
            hour++;
            min = 0;
        }

        assertEquals(t.toLocalDate(), d);
        assertEquals(t.getHour(), hour);
        assertEquals(t.getMinute(), min);
    }
}
 
Example 3
@Test
public void test_plusMinutes_fromZero() {
    LocalDateTime base = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
    LocalDate d = base.toLocalDate().minusDays(1);
    LocalTime t = LocalTime.of(22, 49);

    for (int i = -70; i < 70; i++) {
        LocalDateTime dt = base.plusMinutes(i);
        t = t.plusMinutes(1);

        if (t.equals(LocalTime.MIDNIGHT)) {
            d = d.plusDays(1);
        }

        assertEquals(dt.toLocalDate(), d, String.valueOf(i));
        assertEquals(dt.toLocalTime(), t, String.valueOf(i));
    }
}
 
Example 4
@Test
public void test_plusMinutes_one() {
    LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
    LocalDate d = t.toLocalDate();

    int hour = 0;
    int min = 0;

    for (int i = 0; i < 70; i++) {
        t = t.plusMinutes(1);
        min++;
        if (min == 60) {
            hour++;
            min = 0;
        }

        assertEquals(t.toLocalDate(), d);
        assertEquals(t.getHour(), hour);
        assertEquals(t.getMinute(), min);
    }
}
 
Example 5
@Test
public void test_plusMinutes_one() {
    LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
    LocalDate d = t.toLocalDate();

    int hour = 0;
    int min = 0;

    for (int i = 0; i < 70; i++) {
        t = t.plusMinutes(1);
        min++;
        if (min == 60) {
            hour++;
            min = 0;
        }

        assertEquals(t.toLocalDate(), d);
        assertEquals(t.getHour(), hour);
        assertEquals(t.getMinute(), min);
    }
}
 
Example 6
Source Project: litemall   File: TaskStartupRunner.java    License: MIT License 6 votes vote down vote up
@Override
public void run(ApplicationArguments args) throws Exception {
    List<LitemallOrder> orderList = orderService.queryUnpaid(SystemConfig.getOrderUnpaid());
    for(LitemallOrder order : orderList){
        LocalDateTime add = order.getAddTime();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expire =  add.plusMinutes(SystemConfig.getOrderUnpaid());
        if(expire.isBefore(now)) {
            // 已经过期,则加入延迟队列
            taskService.addTask(new OrderUnpaidTask(order.getId(), 0));
        }
        else{
            // 还没过期,则加入延迟队列
            long delay = ChronoUnit.MILLIS.between(now, expire);
            taskService.addTask(new OrderUnpaidTask(order.getId(), delay));
        }
    }
}
 
Example 7
@Test
public void test_plusMinutes_one() {
    LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
    LocalDate d = t.toLocalDate();

    int hour = 0;
    int min = 0;

    for (int i = 0; i < 70; i++) {
        t = t.plusMinutes(1);
        min++;
        if (min == 60) {
            hour++;
            min = 0;
        }

        assertEquals(t.toLocalDate(), d);
        assertEquals(t.getHour(), hour);
        assertEquals(t.getMinute(), min);
    }
}
 
Example 8
@Test
public void test_plusMinutes_one() {
    LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
    LocalDate d = t.toLocalDate();

    int hour = 0;
    int min = 0;

    for (int i = 0; i < 70; i++) {
        t = t.plusMinutes(1);
        min++;
        if (min == 60) {
            hour++;
            min = 0;
        }

        assertEquals(t.toLocalDate(), d);
        assertEquals(t.getHour(), hour);
        assertEquals(t.getMinute(), min);
    }
}
 
Example 9
Source Project: j2objc   File: TCKLocalDateTime.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_plusMinutes_fromZero() {
    LocalDateTime base = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
    LocalDate d = base.toLocalDate().minusDays(1);
    LocalTime t = LocalTime.of(22, 49);

    for (int i = -70; i < 70; i++) {
        LocalDateTime dt = base.plusMinutes(i);
        t = t.plusMinutes(1);

        if (t.equals(LocalTime.MIDNIGHT)) {
            d = d.plusDays(1);
        }

        assertEquals(String.valueOf(i), dt.toLocalDate(), d);
        assertEquals(String.valueOf(i), dt.toLocalTime(), t);
    }
}
 
Example 10
Source Project: Java-Coding-Problems   File: Main.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {              
    
    System.out.println("Working with Date: ");
    Date date = new Date();
    Date dateAfterAddingYears = DateTimes.addOrSubtractYears(date, 2);
    Date dateAfterSubtractingYears = DateTimes.addOrSubtractYears(date, -2);
    System.out.println("Before adding 2 years: " + date
            + "\nAfter adding 2 years: " + dateAfterAddingYears
            + "\nAfter subtracting 2 years: " + dateAfterSubtractingYears);
    
    Date dateAfterAddingHours = DateTimes.addOrSubtractHours(date, 5);
    Date dateAfterSubtractingHours = DateTimes.addOrSubtractHours(date, -5);
    System.out.println("\nBefore adding 48 hours: " + date
            + "\nAfter adding 48 hours: " + dateAfterAddingHours
            + "\nAfter subtracting 48 hours: " + dateAfterSubtractingHours);
    
    System.out.println("\nWorking with LocalDateTime (similar for LocalDate, ZonedDateTime, OffsetDateTime): ");
    LocalDateTime ldt = LocalDateTime.now();
    LocalDateTime ldtAfterAddingMinutes = ldt.plusMinutes(10);
    LocalDateTime ldtAfterSubtractingMinutes = ldt.minusMinutes(10);
    System.out.println("Before adding 10 minutes: " + ldt
            + "\nAfter adding 10 minutes: " + ldtAfterAddingMinutes
            + "\nAfter subtracting 10 minutes: " + ldtAfterSubtractingMinutes);
    
    System.out.println("\nWorking with Instant: ");
    Instant timestamp = Instant.now();
    Instant timestampAfterAddingHours = timestamp.plus(5, ChronoUnit.HOURS);
    Instant timestampAfterSubtractingHours = timestamp.minus(5, ChronoUnit.HOURS);
    System.out.println("Before adding 5 hours: " + timestamp
            + "\nAfter adding 5 hours: " + timestampAfterAddingHours
            + "\nAfter subtracting 5 hours: " + timestampAfterSubtractingHours);                
    
    
}
 
Example 11
/**
 * Simulate a job that has run longer than the next fire time such that it misfires.
 */
@Test
public void testTriggerPastDueMisfire() throws Exception {
  JobDetail jobDetail = JobBuilder.newJob(MyNonConcurrentJob.class)
      .storeDurably(true)
      .build();
  jobStore.storeJob(jobDetail, false);

  ZoneId zone = ZoneId.systemDefault();

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  LocalDateTime baseDateTime = LocalDateTime.ofInstant(baseFireTimeDate.toInstant(), zone);
  LocalDateTime startAt = baseDateTime.minusMinutes(5);
  LocalDateTime nextFireTime = startAt.plusMinutes(1);

  CronScheduleBuilder schedule = CronScheduleBuilder.cronSchedule("0 1 * * * ? *");
  OperableTrigger trigger = (OperableTrigger) TriggerBuilder.newTrigger()
      .forJob(jobDetail)
      .withSchedule(schedule)
      .startAt(Date.from(startAt.atZone(zone).toInstant()))
      .build();

  // misfire the trigger and set the next fire time in the past
  trigger.updateAfterMisfire(null);
  trigger.setNextFireTime(Date.from(nextFireTime.atZone(zone).toInstant()));
  jobStore.storeTrigger(trigger, false);

  List<OperableTrigger> acquiredTriggers =
      jobStore.acquireNextTriggers(DateBuilder.evenMinuteDateAfterNow().getTime(), 4, 1000L);
  assertEquals(1, acquiredTriggers.size());
}
 
Example 12
Source Project: jakduk-api   File: UserRepositoryTests.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp(){
    User user = repository.findTopByOrderByIdAsc().get();
    LocalDateTime localDateTime = DateUtils.dateToLocalDateTime(new ObjectId(user.getId()).getDate());
    Long hours = ChronoUnit.MINUTES.between(localDateTime, LocalDateTime.now());
    LocalDateTime randomDate = localDateTime.plusMinutes(new Random().nextInt((int) (hours + 1)));
    randomUser = repository.findTopByIdLessThanEqualOrderByIdDesc(new ObjectId(DateUtils.localDateTimeToDate(randomDate))).get();
}
 
Example 13
Source Project: mall   File: OrderJob.java    License: MIT License 5 votes vote down vote up
/**
 * 自动取消订单
 * <p>
 * 定时检查订单未付款情况,如果超时半个小时则自动取消订单
 * 定时时间是每次相隔半个小时。
 * <p>
 * 注意,因为是相隔半小时检查,因此导致有订单是超时一个小时以后才设置取消状态。
 * TODO
 * 这里可以进一步地配合用户订单查询时订单未付款检查,如果订单超时半小时则取消。
 */
@Scheduled(fixedDelay = 30 * 60 * 1000)
@Transactional
public void checkOrderUnpaid() {
    logger.info("系统开启任务检查订单是否已经超期自动取消订单");

    List<LitemallOrder> orderList = orderService.queryUnpaid();
    for (LitemallOrder order : orderList) {
        LocalDateTime add = order.getAddTime();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expired = add.plusMinutes(30);
        if (expired.isAfter(now)) {
            continue;
        }

        // 设置订单已取消状态
        order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
        order.setEndTime(LocalDateTime.now());
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            throw new RuntimeException("更新数据已失效");
        }

        // 商品货品数量增加
        Integer orderId = order.getId();
        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            Integer productId = orderGoods.getProductId();
            LitemallGoodsProduct product = productService.findById(productId);
            Short number = orderGoods.getNumber();
            if (productService.addStock(productId, number) == 0) {
                throw new RuntimeException("商品货品库存增加失败");
            }
        }
        logger.info("订单 ID=" + order.getId() + " 已经超期自动取消订单");
    }
}
 
Example 14
@Test
public void add_minutes_to_date_in_java8() {

	LocalDateTime newYearsEve = LocalDateTime.of(2012, Month.DECEMBER, 31,
			23, 59);
	LocalDateTime newYearsDay = newYearsEve.plusMinutes(1);

	java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
			.ofPattern("MM/dd/yyyy HH:mm:ss S");

	logger.info(newYearsEve.format(formatter));
	logger.info(newYearsDay.format(formatter));

	assertTrue(newYearsDay.isAfter(newYearsEve));
}
 
Example 15
@Before
public void setUp(){
    ArticleComment articleComment = repository.findTopByOrderByIdAsc().get();
    LocalDateTime localDateTime = DateUtils.dateToLocalDateTime(new ObjectId(articleComment.getId()).getDate());
    Long hours = ChronoUnit.MINUTES.between(localDateTime, LocalDateTime.now());
    LocalDateTime randomDate = localDateTime.plusMinutes(new Random().nextInt((int) (hours + 1)));
    randomArticleComment = repository.findTopByIdLessThanEqualOrderByIdDesc(new ObjectId(DateUtils.localDateTimeToDate(randomDate))).get();
}
 
Example 16
Source Project: short-text-search   File: SearchService.java    License: Apache License 2.0 5 votes vote down vote up
private static void buildLastMinuteIndex(LocalDateTime minute) {
    String minuteStr = TimeUtils.toString(minute, "yyyy-MM-dd HH:mm:00");
    LOGGER.info("开始导出数据, minute: {}", minuteStr);
    long ts = System.currentTimeMillis();
    LocalDateTime start = minute;
    LocalDateTime end = minute.plusMinutes(1);
    long s = System.currentTimeMillis();
    int count = VisitorSource.index(start, end, "minute");
    LOGGER.info("构建分钟索引成功, minute: {}, 数据条数: {}, 总耗时: {}",
            TimeUtils.toString(minute, "yyyy-MM-dd HH:mm:00"),
            count,
            TimeUtils.getTimeDes(System.currentTimeMillis()-s));
}
 
Example 17
/**
 * Simulate a job that has run longer than the next fire time such that it misfires, but will not fire again because
 * the end of the trigger window has passed.
 */
@Test
public void testTriggerPastDueMisfireButWillNotFire() throws Exception {
  JobDetail jobDetail = JobBuilder.newJob(MyNonConcurrentJob.class).storeDurably(true).build();
  jobStore.storeJob(jobDetail, false);

  ZoneId zone = ZoneId.systemDefault();

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  LocalDateTime baseDateTime = LocalDateTime.ofInstant(baseFireTimeDate.toInstant(), zone);
  LocalDateTime startAt = baseDateTime.minusMinutes(5);
  LocalDateTime endAt = baseDateTime.minusMinutes(1);
  LocalDateTime nextFireTime = startAt.plusMinutes(1);

  SimpleScheduleBuilder simple = SimpleScheduleBuilder.simpleSchedule()
      .withIntervalInMinutes(1);
  OperableTrigger trigger = (OperableTrigger) TriggerBuilder.newTrigger()
      .forJob(jobDetail)
      .withSchedule(simple)
      .startAt(Date.from(startAt.atZone(zone).toInstant()))
      .endAt(Date.from(endAt.atZone(zone).toInstant()))
      .build();

  // misfire the trigger and set the next fire time in the past
  trigger.updateAfterMisfire(null);
  trigger.setNextFireTime(Date.from(nextFireTime.atZone(zone).toInstant()));
  trigger.setMisfireInstruction(MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT);
  jobStore.storeTrigger(trigger, false);

  List<OperableTrigger> acquiredTriggers =
      jobStore.acquireNextTriggers(baseFireTimeDate.getTime(), 4, 1000L);
  assertEquals(0, acquiredTriggers.size());
}
 
Example 18
@Test
void testCertRenewalInMaintenanceWindow() {
    String secretName = CLUSTER_NAME + "-cluster-ca-cert";
    LocalDateTime maintenanceWindowStart = LocalDateTime.now().withSecond(0);
    long maintenanceWindowDuration = 14;
    maintenanceWindowStart = maintenanceWindowStart.plusMinutes(5);
    long windowStartMin = maintenanceWindowStart.getMinute();
    long windowStopMin = windowStartMin + maintenanceWindowDuration > 59
            ? windowStartMin + maintenanceWindowDuration - 60 : windowStartMin + maintenanceWindowDuration;

    String maintenanceWindowCron = "* " + windowStartMin + "-" + windowStopMin + " * * * ? *";
    LOGGER.info("Maintenance window is: {}", maintenanceWindowCron);
    KafkaResource.kafkaPersistent(CLUSTER_NAME, 3, 1)
            .editSpec()
                .addNewMaintenanceTimeWindow(maintenanceWindowCron)
            .endSpec().done();

    KafkaUser user = KafkaUserResource.tlsUser(CLUSTER_NAME, KafkaUserUtils.generateRandomNameOfKafkaUser()).done();
    String topicName = KafkaTopicUtils.generateRandomNameOfTopic();

    KafkaTopicResource.topic(CLUSTER_NAME, topicName).done();
    KafkaClientsResource.deployKafkaClients(true, CLUSTER_NAME + "-" + Constants.KAFKA_CLIENTS, user).done();

    String defaultKafkaClientsPodName =
            ResourceManager.kubeClient().listPodsByPrefixInName(CLUSTER_NAME + "-" + Constants.KAFKA_CLIENTS).get(0).getMetadata().getName();

    InternalKafkaClient internalKafkaClient = new InternalKafkaClient.Builder()
        .withUsingPodName(defaultKafkaClientsPodName)
        .withTopicName(topicName)
        .withNamespaceName(NAMESPACE)
        .withClusterName(CLUSTER_NAME)
        .withMessageCount(MESSAGE_COUNT)
        .withKafkaUsername(user.getMetadata().getName())
        .build();

    Map<String, String> kafkaPods = StatefulSetUtils.ssSnapshot(kafkaStatefulSetName(CLUSTER_NAME));

    LOGGER.info("Annotate secret {} with secret force-renew annotation", secretName);
    Secret secret = new SecretBuilder(kubeClient().getSecret(secretName))
        .editMetadata()
            .addToAnnotations(Ca.ANNO_STRIMZI_IO_FORCE_RENEW, "true")
        .endMetadata().build();
    kubeClient().patchSecret(secretName, secret);

    LOGGER.info("Wait until maintenance windows starts");
    LocalDateTime finalMaintenanceWindowStart = maintenanceWindowStart;
    TestUtils.waitFor("maintenance window start",
        Constants.GLOBAL_POLL_INTERVAL, Duration.ofMinutes(maintenanceWindowDuration).toMillis() - 10000,
        () -> LocalDateTime.now().isAfter(finalMaintenanceWindowStart));

    LOGGER.info("Maintenance window starts");

    assertThat("Rolling update was performed out of maintenance window!", kafkaPods, is(StatefulSetUtils.ssSnapshot(kafkaStatefulSetName(CLUSTER_NAME))));

    LOGGER.info("Wait until rolling update is triggered during maintenance window");
    StatefulSetUtils.waitTillSsHasRolled(kafkaStatefulSetName(CLUSTER_NAME), 3, kafkaPods);

    assertThat("Rolling update wasn't performed in correct time", LocalDateTime.now().isAfter(maintenanceWindowStart));

    LOGGER.info("Checking consumed messages to pod:{}", defaultKafkaClientsPodName);

    internalKafkaClient.checkProducedAndConsumedMessages(
        internalKafkaClient.sendMessagesTls(),
        internalKafkaClient.receiveMessagesTls()
    );
}
 
Example 19
private static LocalDateTime nextPublishingTime(LocalDateTime previous) {
    return previous.plusMinutes(nextInt(PUBLISHING_TIME_MAX_DIFF - 1) + 1);
}
 
Example 20
/**
 * 计算 minute 分钟后的时间.
 *
 * @param date   长日期
 * @param minute 需要增加的分钟数
 * @return 增加后的日期 local date time
 */
public static LocalDateTime addMinute(final LocalDateTime date, final int minute) {
    return date.plusMinutes(minute);
}