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

The following examples show how to use java.time.LocalDateTime#plusDays() . 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
Source Project: salespoint   File: IntervalUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test // #153
void detectsContainedDateTimes() {

	LocalDateTime now = LocalDateTime.now();
	LocalDateTime nowTomorrow = now.plusDays(1);
	LocalDateTime nowYesterday = now.minusDays(1);

	Interval interval = Interval.from(nowYesterday).to(nowTomorrow);

	assertThat(interval.contains(now), is(true));
	assertThat(interval.contains(nowTomorrow), is(true));
	assertThat(interval.contains(nowYesterday), is(true));

	assertThat(interval.contains(nowYesterday.minusDays(1)), is(false));
	assertThat(interval.contains(nowTomorrow.plusDays(1)), is(false));
}
 
Example 2
/**
 * 可评价订单商品超期
 * <p>
 * 定时检查订单商品评价情况,如果确认商品超时七天则取消可评价状态 定时时间是每天凌晨4点。
 */
@Scheduled(cron = "0 0 4 * * ?")
public void checkOrderComment() {
	logger.info("系统开启任务检查订单是否已经超期未评价");

	LocalDateTime now = LocalDateTime.now();
	List<DtsOrder> orderList = orderService.queryComment();
	for (DtsOrder order : orderList) {
		LocalDateTime confirm = order.getConfirmTime();
		LocalDateTime expired = confirm.plusDays(7);
		if (expired.isAfter(now)) {
			continue;
		}

		order.setComments((short) 0);
		orderService.updateWithOptimisticLocker(order);

		List<DtsOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());
		for (DtsOrderGoods orderGoods : orderGoodsList) {
			orderGoods.setComment(-1);
			orderGoodsService.updateById(orderGoods);
		}
	}
}
 
Example 3
public LocalDateTime updateDay(LocalDateTime datetime, String day) {
  if (!Strings.isNullOrEmpty(day)) {
    Matcher matcher = patternMonth.matcher(day);
    if (matcher.find()) {
      Long days = Long.parseLong(matcher.group());
      if (day.startsWith("+")) datetime = datetime.plusDays(days);
      else if (day.startsWith("-")) datetime = datetime.minusDays(days);
      else {
        if (days > datetime.toLocalDate().lengthOfMonth()) {
          days = Long.valueOf(datetime.toLocalDate().lengthOfMonth());
        }
        datetime = datetime.withDayOfMonth(days.intValue());
      }
    }
  }
  return datetime;
}
 
Example 4
private Interval createOptionalEnergyIntervalForEVCharger(LocalDateTime now,
                                                          TimeframeInterval predecessor,
                                                          TimeframeInterval successor) {
    LocalDateTime timeframeStart = LocalDateTime.from(now);
    LocalDateTime timeframeEnd = timeframeStart.plusDays(CONSIDERATION_INTERVAL_DAYS);
    if(predecessor != null) {
        timeframeStart = predecessor.getInterval().getEnd().plusSeconds(1);
    }
    if(successor != null) {
        timeframeEnd = successor.getInterval().getStart().minusSeconds(1);
    }
    if(timeframeStart.isBefore(timeframeEnd)) {
        return new Interval(timeframeStart, timeframeEnd);
    }
    return null;
}
 
Example 5
@Test
public void testTimeWindow() {
  LocalDateTime dateTime = LocalDateTime.of(2018, 4, 10, 7, 30);
  startCol.append(dateTime);
  for (int i = 0; i < 49; i++) {
    dateTime = dateTime.plusDays(1);
    startCol.append(dateTime);
  }
  LongColumn timeWindows = startCol.timeWindow(ChronoUnit.DAYS, 5);
  assertEquals(0, timeWindows.get(0), 0.0001);
  assertEquals(9, timeWindows.max(), 0.0001);

  timeWindows = startCol.timeWindow(ChronoUnit.WEEKS, 1);
  assertEquals(0, timeWindows.get(0), 0.0001);
  assertEquals(7, timeWindows.max(), 0.0001);

  timeWindows = startCol.timeWindow(ChronoUnit.MONTHS, 1);
  assertEquals(0, timeWindows.get(0), 0.0001);
  assertEquals(1, timeWindows.max(), 0.0001);

  timeWindows = startCol.timeWindow(ChronoUnit.YEARS, 1);
  assertEquals(0, timeWindows.get(0), 0.0001);
  assertEquals(0, timeWindows.max(), 0.0001);
}
 
Example 6
@Test
public void testTimeWindow() {
  LocalDateTime dateTime = LocalDateTime.of(2018, 4, 10, 7, 30);
  startCol.append(dateTime);
  for (int i = 0; i < 49; i++) {
    dateTime = dateTime.plusDays(1);
    startCol.append(dateTime);
  }
  LongColumn timeWindows = startCol.timeWindow(ChronoUnit.DAYS, 5);
  assertEquals(0, timeWindows.get(0), 0.0001);
  assertEquals(9, timeWindows.max(), 0.0001);

  timeWindows = startCol.timeWindow(ChronoUnit.WEEKS, 1);
  assertEquals(0, timeWindows.get(0), 0.0001);
  assertEquals(7, timeWindows.max(), 0.0001);

  timeWindows = startCol.timeWindow(ChronoUnit.MONTHS, 1);
  assertEquals(0, timeWindows.get(0), 0.0001);
  assertEquals(1, timeWindows.max(), 0.0001);

  timeWindows = startCol.timeWindow(ChronoUnit.YEARS, 1);
  assertEquals(0, timeWindows.get(0), 0.0001);
  assertEquals(0, timeWindows.max(), 0.0001);
}
 
Example 7
@Override
public Temporal adjustInto(Temporal temporal) {

	LocalDateTime currentDateTime = LocalDateTime.from(temporal);

	LocalDateTime futureDate = LocalDateTime.from(temporal).plus(90,
			ChronoUnit.DAYS);

	for (LocalDateTime startDate = currentDateTime; startDate
			.isBefore(futureDate); startDate = startDate.plusDays(1)) {

		if (startDate.query(new WeekendQuery())) {
			futureDate = futureDate.plusDays(1);
		}
	}
	return futureDate;
}
 
Example 8
public static void main(String[] args) throws IOException {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	String s;
	while (!(s=br.readLine()).equals("0 0 0 0")) {
		StringTokenizer st=new StringTokenizer(s);
		//Java 8's library
		int [] data=new int [] {Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken())};
		LocalDateTime currentTime=LocalDateTime.of(data[3], data[2], data[1], 0, 0);
		currentTime=currentTime.plusDays(data[0]);
		System.out.println(currentTime.getDayOfMonth()+" "+currentTime.getMonthValue()+" "+currentTime.getYear());
	}
}
 
Example 9
Source Project: FX-AlgorithmTrading   File: MarketTimeUtility.java    License: MIT License 5 votes vote down vote up
/**
 * 次の Market Open 時刻を取得します
 * @param jstDateTime
 * @return
 */
public static LocalDateTime getNextOpenTime(LocalDateTime jstDateTime) {
    // まずSummerで計算する
    LocalDateTime nextOpenTime = LocalDateTime.of(jstDateTime.getYear(), jstDateTime.getMonth(), jstDateTime.getDayOfMonth(),
            OPEN_WEEEK_MONDAY_SUMMER.getHour(), OPEN_WEEEK_MONDAY_SUMMER.getMinute());
    while (nextOpenTime.getDayOfWeek() != DayOfWeek.MONDAY) {
        nextOpenTime = nextOpenTime.plusDays(1);
    }
    // 日付が確定したら夏冬判定する
    if (isNYCSummer(nextOpenTime.toLocalDate())) {
        return nextOpenTime;
    } else {
        return nextOpenTime.withHour(OPEN_WEEEK_MONDAY_WINTER.getHour());
    }
}
 
Example 10
Source Project: salespoint   File: IntervalUnitTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test // #8
void instancesWithSameStartAndEndAreEqual() {

	LocalDateTime start = LocalDateTime.now();
	LocalDateTime end = start.plusDays(2);

	Interval first = Interval.from(start).to(end);
	Interval second = Interval.from(start).to(end);

	assertThat(first, is(first));
	assertThat(first, is(second));
	assertThat(second, is(first));
}
 
Example 11
public LocalDateTime toNextOccurrence(LocalDateTime now) {
    LocalDateTime dateTime = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(),
            getHour(), getMinute(), getSecond());
    while(dateTime.getDayOfWeek().getValue() != dayOfWeek) {
        dateTime = dateTime.plusDays(1);
    }
    return dateTime;
}
 
Example 12
@Test
public void add_days_to_date_in_java8() {

	LocalDateTime superBowlXLV = LocalDateTime.of(2011, Month.FEBRUARY, 6,
			0, 0);
	LocalDateTime celebration = superBowlXLV.plusDays(1);

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

	logger.info(superBowlXLV.format(formatter));
	logger.info(celebration.format(formatter));

	assertTrue(celebration.isAfter(superBowlXLV));
}
 
Example 13
Source Project: tutorials   File: UseLocalDateTimeUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenLocalDateTime_whenManipulating_thenResultIsAsExpected() {
    LocalDateTime givenLocalDateTime = LocalDateTime.parse("2015-02-20T06:30:00");

    LocalDateTime manipulatedLocalDateTime = givenLocalDateTime.plusDays(1);
    manipulatedLocalDateTime = manipulatedLocalDateTime.minusHours(2);

    assertThat(manipulatedLocalDateTime).isEqualTo(LocalDateTime.of(2015, Month.FEBRUARY, 21, 4, 30));
}
 
Example 14
private static List<Map<String, Object>> getDayData(int startYear, int startMonth, int startDay){
    List<Map<String, Object>> data = new ArrayList<>();
    LocalDateTime start = LocalDateTime.of(startYear, startMonth, startDay, 0, 0, 0, 0);
    LocalDateTime end = LocalDateTime.now();
    while(start.isBefore(end)) {
        String date = TimeUtils.toString(start, "yyyy-MM-dd");
        int dayofweek = start.getDayOfWeek().getValue();
        int dayofyear = start.getDayOfYear();
        int weekofyear = ((dayofyear-1) / 7)+1;
        int month = start.getMonth().getValue();
        int dayofmonth = start.getDayOfMonth();
        int quarter = ((month-1) / 3) + 1;
        int year = start.getYear();
        Map<String, Object> map = new HashMap<>();
        map.put("day_str", date+" 00:00:00");
        map.put("dayofweek", dayofweek);
        map.put("dayofyear", dayofyear);
        map.put("weekofyear", weekofyear);
        map.put("month", month);
        map.put("dayofmonth", dayofmonth);
        map.put("quarter", quarter);
        map.put("year", year);
        data.add(map);
        start = start.plusDays(1);
    }
    return data;
}
 
Example 15
@Test
public void optionalEnergyRequest_SocScript_MaxSocGTInitialSoc() {
    LocalDateTime timeInitial = toToday(9, 50, 0);
    defaultSocOptionalEnergy = 80;
    Appliance appliance = new ApplianceBuilder(applianceId)
            .withEvCharger(evChargerControl)
            .withElectricVehicle(evId, batteryCapacity, defaultSocOptionalEnergy, null)
            .withMeter(meter)
            .build(true);
    TimeframeIntervalHandler timeframeIntervalHandler = appliance.getTimeframeIntervalHandler();
    ElectricVehicleCharger evCharger = (ElectricVehicleCharger) appliance.getControl();

    log("Vehicle not connected", timeInitial);
    tick(appliance, timeInitial, false, false);
    assertEquals(0, timeframeIntervalHandler.getQueue().size());

    LocalDateTime timeVehicleConnected = toToday(9, 55, 0);
    log("Vehicle connected", timeVehicleConnected);
    Interval interval = new Interval(timeVehicleConnected,
            timeVehicleConnected.plusDays(TimeframeIntervalHandler.CONSIDERATION_INTERVAL_DAYS));
    Mockito.doReturn(70.0f).when(evCharger).getStateOfCharge(Mockito.any());
    tick(appliance, timeVehicleConnected, true, false);
    assertEquals(1, timeframeIntervalHandler.getQueue().size());
    assertTimeframeIntervalOptionalEnergy(interval, TimeframeIntervalState.ACTIVE,
            70, defaultSocOptionalEnergy, evId, 4400, true,
            timeframeIntervalHandler.getQueue().get(0));
}
 
Example 16
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/repository/oneHumanTaskCase.cmmn" })
public void testUpdateLocalDateTimeProcessVariable() throws Exception {

    LocalDateTime initial = LocalDateTime.parse("2020-01-18T12:32:45");
    LocalDateTime tenDaysLater = initial.plusDays(10);
    CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase")
            .variables(Collections.singletonMap("overlappingVariable", (Object) "processValue")).start();
    runtimeService.setVariable(caseInstance.getId(), "myVar", initial);

    // Update variable
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("name", "myVar");
    requestNode.put("value", "2020-01-28T12:32:45");
    requestNode.put("type", "localDateTime");

    HttpPut httpPut = new HttpPut(
            SERVER_URL_PREFIX + CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_CASE_INSTANCE_VARIABLE, caseInstance.getId(), "myVar"));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

    assertThatJson(runtimeService.getVariable(caseInstance.getId(), "myVar")).isEqualTo(tenDaysLater);

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertThat(responseNode).isNotNull();
    assertThatJson(responseNode)
            .when(Option.IGNORING_EXTRA_FIELDS)
            .isEqualTo("{"
                    + "  value: '2020-01-28T12:32:45'"
                    + "}");
}
 
Example 17
Source Project: schedge   File: ParseCatalog.java    License: MIT License 4 votes vote down vote up
List<Meeting> parseSectionTimesData(String times, String dates)
    throws IOException {
  logger.trace("Parsing section times data...");
  // MoWe 9:30am - 10:45am Fr
  // 2:00pm - 4:00pm Fr 2:00pm - 4:00pm

  Iterator<String> timeTokens = Arrays.asList(times.split(" "))
                                    .stream()
                                    .filter(s -> !s.equals("-"))
                                    .iterator();

  // 09/03/2019 - 12/13/2019 10/11/2019
  // - 10/11/2019 11/08/2019 - 11/08/2019
  Iterator<String> dateTokens = Arrays.asList(dates.split(" "))
                                    .stream()
                                    .filter(s -> !s.equals("-"))
                                    .iterator();

  ArrayList<Meeting> meetings = new ArrayList<>();
  while (timeTokens.hasNext()) {
    if (!dateTokens.hasNext()) {
      logger.error("Time/date was in unexpected format: time='{}', date='{}'",
                   times, dates);
      throw new IOException("Time/date was in unexpected format");
    }

    String beginDays = timeTokens.next();

    if (beginDays.equals("TBA")) {
      safeNext(dateTokens);
      safeNext(dateTokens);
      continue;
    }

    LocalDateTime beginDateTime;
    long duration;
    {
      String beginDateString = dateTokens.next();

      beginDateTime = LocalDateTime.from(timeParser.parse(
          beginDateString + ' ' + timeTokens.next().toUpperCase()));
      LocalDateTime stopDateTime = LocalDateTime.from(timeParser.parse(
          beginDateString + ' ' + timeTokens.next().toUpperCase()));
      // logger.trace("Begin date: {}, End date: {}", beginDateTime,
      //             stopDateTime);
      duration = ChronoUnit.MINUTES.between(beginDateTime, stopDateTime);
      // logger.trace("Duration of meeting is {} minutes", duration);
    }

    LocalDateTime endDate =
        LocalDateTime.from(timeParser.parse(dateTokens.next() + " 11:59PM"));

    boolean[] daysList = new boolean[7];
    Arrays.fill(daysList, Boolean.FALSE);
    for (int i = 0; i < beginDays.length() - 1; i += 2) {
      String dayString = beginDays.substring(i, i + 2);
      int dayValue = Utils.parseDayOfWeek(dayString).getValue();
      // logger.trace("day: {} translates to ", dayString, dayValue);
      daysList[dayValue % 7] = true;
    }

    for (int day = 0; day < 7;
         day++, beginDateTime = beginDateTime.plusDays(1)) {
      if (daysList[beginDateTime.getDayOfWeek().getValue() % 7]) {
        meetings.add(new Meeting(beginDateTime, duration, endDate));
      }
    }
  }
  // logger.trace("Meetings are: {}", meetings);

  return meetings;
}
 
Example 18
@Test
@Deployment(resources = { "org/flowable/engine/test/api/oneTaskProcess.bpmn20.xml" })
public void testQueryLocalDateTimeVariable() throws Exception {
    Map<String, Object> vars = new HashMap<>();
    LocalDateTime localDateTime = LocalDateTime.now();
    vars.put("localDateTimeVar", localDateTime);

    ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);

    LocalDateTime localDateTime2 = localDateTime.plusDays(1);
    vars = new HashMap<>();
    vars.put("localDateTimeVar", localDateTime);
    vars.put("localDateTimeVar2", localDateTime2);
    ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);

    LocalDateTime nextYear = localDateTime.plusYears(1);
    vars = new HashMap<>();
    vars.put("localDateTimeVar", nextYear);
    ProcessInstance processInstance3 = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);

    LocalDateTime nextMonth = localDateTime.plusMonths(1);

    LocalDateTime twoYearsLater = localDateTime.plusYears(2);

    LocalDateTime oneYearAgo = localDateTime.minusYears(1);

    // Query on single localDateTime variable, should result in 2 matches
    ExecutionQuery query = runtimeService.createExecutionQuery().variableValueEquals("localDateTimeVar", localDateTime);
    List<Execution> executions = query.list();
    assertThat(executions).hasSize(2);

    // Query on two localDateTime variables, should result in single value
    query = runtimeService.createExecutionQuery().variableValueEquals("localDateTimeVar", localDateTime).variableValueEquals("localDateTimeVar2", localDateTime2);
    Execution execution = query.singleResult();
    assertThat(execution).isNotNull();
    assertThat(execution.getId()).isEqualTo(processInstance2.getId());

    // Query with unexisting variable value
    execution = runtimeService.createExecutionQuery().variableValueEquals("localDateTimeVar", localDateTime.minusDays(1)).singleResult();
    assertThat(execution).isNull();

    // Test NOT_EQUALS
    execution = runtimeService.createExecutionQuery().variableValueNotEquals("localDateTimeVar", localDateTime).singleResult();
    assertThat(execution).isNotNull();
    assertThat(execution.getId()).isEqualTo(processInstance3.getId());

    // Test GREATER_THAN
    execution = runtimeService.createExecutionQuery().variableValueGreaterThan("localDateTimeVar", nextMonth).singleResult();
    assertThat(execution).isNotNull();
    assertThat(execution.getId()).isEqualTo(processInstance3.getId());

    assertThat(runtimeService.createExecutionQuery().variableValueGreaterThan("localDateTimeVar", nextYear).count()).isZero();
    assertThat(runtimeService.createExecutionQuery().variableValueGreaterThan("localDateTimeVar", oneYearAgo).count()).isEqualTo(3);

    // Test GREATER_THAN_OR_EQUAL
    execution = runtimeService.createExecutionQuery().variableValueGreaterThanOrEqual("localDateTimeVar", nextMonth).singleResult();
    assertThat(execution).isNotNull();
    assertThat(execution.getId()).isEqualTo(processInstance3.getId());

    execution = runtimeService.createExecutionQuery().variableValueGreaterThanOrEqual("localDateTimeVar", nextYear).singleResult();
    assertThat(execution).isNotNull();
    assertThat(execution.getId()).isEqualTo(processInstance3.getId());

    assertThat(runtimeService.createExecutionQuery().variableValueGreaterThanOrEqual("localDateTimeVar", oneYearAgo).count()).isEqualTo(3);

    // Test LESS_THAN
    executions = runtimeService.createExecutionQuery().variableValueLessThan("localDateTimeVar", nextYear).list();
    assertThat(executions)
        .extracting(Execution::getId)
        .containsExactlyInAnyOrder(
            processInstance1.getId(),
            processInstance2.getId()
        );

    assertThat(runtimeService.createExecutionQuery().variableValueLessThan("localDateTimeVar", localDateTime).count()).isZero();
    assertThat(runtimeService.createExecutionQuery().variableValueLessThan("localDateTimeVar", twoYearsLater).count()).isEqualTo(3);

    // Test LESS_THAN_OR_EQUAL
    executions = runtimeService.createExecutionQuery().variableValueLessThanOrEqual("localDateTimeVar", nextYear).list();
    assertThat(executions).hasSize(3);

    assertThat(runtimeService.createExecutionQuery().variableValueLessThanOrEqual("localDateTimeVar", oneYearAgo).count()).isZero();

    // Test value-only matching
    execution = runtimeService.createExecutionQuery().variableValueEquals(nextYear).singleResult();
    assertThat(execution).isNotNull();
    assertThat(execution.getId()).isEqualTo(processInstance3.getId());

    executions = runtimeService.createExecutionQuery().variableValueEquals(localDateTime).list();
    assertThat(executions)
        .extracting(Execution::getId)
        .containsExactlyInAnyOrder(
            processInstance1.getId(),
            processInstance2.getId()
        );

    execution = runtimeService.createExecutionQuery().variableValueEquals(twoYearsLater).singleResult();
    assertThat(execution).isNull();
}
 
Example 19
Source Project: graphql-java-datetime   File: Mutation.java    License: Apache License 2.0 4 votes vote down vote up
public LocalDateTime plusDay(LocalDateTime input) {
    return input.plusDays(1);
}
 
Example 20
Source Project: Lottor   File: DateUtils.java    License: MIT License 2 votes vote down vote up
/**
 * 计算 day 天后的时间
 *
 * @param date 长日期
 * @param day  增加的天数
 * @return 增加后的日期
 */
public static LocalDateTime addDay(LocalDateTime date, int day) {
    return date.plusDays(day);
}