Java Code Examples for java.time.ZonedDateTime#minus()

The following examples show how to use java.time.ZonedDateTime#minus() . 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 File: DefaultEntityResponseBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void notModifiedLastModified() throws ServletException, IOException {
	ZonedDateTime now = ZonedDateTime.now();
	ZonedDateTime oneMinuteBeforeNow = now.minus(1, ChronoUnit.MINUTES);

	EntityResponse<String> entityResponse = EntityResponse.fromObject("bar")
			.lastModified(oneMinuteBeforeNow)
			.build();

	MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "https://example.com");
	mockRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateTimeFormatter.RFC_1123_DATE_TIME.format(now));

	MockHttpServletResponse mockResponse = new MockHttpServletResponse();

	ModelAndView mav = entityResponse.writeTo(mockRequest, mockResponse, EMPTY_CONTEXT);
	assertNull(mav);

	assertEquals(HttpStatus.NOT_MODIFIED.value(), mockResponse.getStatus());
}
 
Example 2
Source File: Calendar.java    From calendar-component with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a date that is last day in the week that target given date belongs
 * to.
 *
 * @param date
 *            Target date
 * @return Date that is last date in same week that given date is.
 */
protected ZonedDateTime getLastDayOfWeek(ZonedDateTime date) {

    DayOfWeek firstDayOfWeek = getFirstDayOfWeek();

    date = date.plus(1, ChronoUnit.DAYS);

    // Roll to weeks last day using firstdayofweek. Roll until FDofW is
    // found and then roll back one day.
    while (firstDayOfWeek != date.getDayOfWeek()) {
        date = date.plus(1, ChronoUnit.DAYS);
    }

    date = date.minus(1, ChronoUnit.DAYS);

    return date;
}
 
Example 3
Source File: DefaultEntityResponseBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void notModifiedLastModified() {
	ZonedDateTime now = ZonedDateTime.now();
	ZonedDateTime oneMinuteBeforeNow = now.minus(1, ChronoUnit.MINUTES);

	EntityResponse<String> responseMono = EntityResponse.fromObject("bar")
			.lastModified(oneMinuteBeforeNow)
			.build()
			.block();

	MockServerHttpRequest request = MockServerHttpRequest.get("http://example.com")
			.header(HttpHeaders.IF_MODIFIED_SINCE,
					DateTimeFormatter.RFC_1123_DATE_TIME.format(now))
			.build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);

	responseMono.writeTo(exchange, DefaultServerResponseBuilderTests.EMPTY_CONTEXT);

	MockServerHttpResponse response = exchange.getResponse();
	assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode());
	StepVerifier.create(response.getBody())
			.expectError(IllegalStateException.class)
			.verify();
}
 
Example 4
Source File: DefaultServerResponseBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void notModifiedLastModified() {
	ZonedDateTime now = ZonedDateTime.now();
	ZonedDateTime oneMinuteBeforeNow = now.minus(1, ChronoUnit.MINUTES);

	ServerResponse responseMono = ServerResponse.ok()
			.lastModified(oneMinuteBeforeNow)
			.syncBody("bar")
			.block();

	MockServerHttpRequest request = MockServerHttpRequest.get("http://example.com")
			.header(HttpHeaders.IF_MODIFIED_SINCE,
					DateTimeFormatter.RFC_1123_DATE_TIME.format(now))
			.build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);

	responseMono.writeTo(exchange, EMPTY_CONTEXT);

	MockServerHttpResponse response = exchange.getResponse();
	assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode());
	StepVerifier.create(response.getBody())
			.expectError(IllegalStateException.class)
			.verify();
}
 
Example 5
Source File: DefaultRenderingResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void notModifiedLastModified() throws Exception {
	ZonedDateTime now = ZonedDateTime.now();
	ZonedDateTime oneMinuteBeforeNow = now.minus(1, ChronoUnit.MINUTES);

	RenderingResponse result = RenderingResponse.create("bar")
			.header(HttpHeaders.LAST_MODIFIED, DateTimeFormatter.RFC_1123_DATE_TIME.format(oneMinuteBeforeNow))
			.build();

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "https://example.com");
	request.addHeader(HttpHeaders.IF_MODIFIED_SINCE,DateTimeFormatter.RFC_1123_DATE_TIME.format(now));
	MockHttpServletResponse response = new MockHttpServletResponse();

	ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT);
	assertNull(mav);
	assertEquals(HttpStatus.NOT_MODIFIED.value(), response.getStatus());
}
 
Example 6
Source File: DefaultServerResponseBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void notModifiedLastModified() throws Exception {
	ZonedDateTime now = ZonedDateTime.now();
	ZonedDateTime oneMinuteBeforeNow = now.minus(1, ChronoUnit.MINUTES);

	ServerResponse response = ServerResponse.ok()
			.lastModified(oneMinuteBeforeNow)
			.body("bar");

	MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "https://example.com");
	mockRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateTimeFormatter.RFC_1123_DATE_TIME.format(now));

	MockHttpServletResponse mockResponse = new MockHttpServletResponse();
	ModelAndView mav = response.writeTo(mockRequest, mockResponse, EMPTY_CONTEXT);
	assertNull(mav);

	assertEquals(HttpStatus.NOT_MODIFIED.value(), mockResponse.getStatus());
}
 
Example 7
Source File: DefaultRenderingResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void notModifiedLastModified() {
	ZonedDateTime now = ZonedDateTime.now();
	ZonedDateTime oneMinuteBeforeNow = now.minus(1, ChronoUnit.MINUTES);

	RenderingResponse responseMono = RenderingResponse.create("bar")
			.header(HttpHeaders.LAST_MODIFIED, DateTimeFormatter.RFC_1123_DATE_TIME.format(oneMinuteBeforeNow))
			.build()
			.block();

	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.com")
			.header(HttpHeaders.IF_MODIFIED_SINCE,
					DateTimeFormatter.RFC_1123_DATE_TIME.format(now))
			.build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);

	responseMono.writeTo(exchange, DefaultServerResponseBuilderTests.EMPTY_CONTEXT);

	MockServerHttpResponse response = exchange.getResponse();
	assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode());
	StepVerifier.create(response.getBody())
			.expectError(IllegalStateException.class)
			.verify();
}
 
Example 8
Source File: DefaultServerResponseBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void notModifiedLastModified() {
	ZonedDateTime now = ZonedDateTime.now();
	ZonedDateTime oneMinuteBeforeNow = now.minus(1, ChronoUnit.MINUTES);

	ServerResponse responseMono = ServerResponse.ok()
			.lastModified(oneMinuteBeforeNow)
			.syncBody("bar")
			.block();

	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.com")
			.header(HttpHeaders.IF_MODIFIED_SINCE,
					DateTimeFormatter.RFC_1123_DATE_TIME.format(now))
			.build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);

	responseMono.writeTo(exchange, EMPTY_CONTEXT);

	MockServerHttpResponse response = exchange.getResponse();
	assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode());
	StepVerifier.create(response.getBody())
			.expectError(IllegalStateException.class)
			.verify();
}
 
Example 9
Source File: MinusTimeFilter.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Override
public Object filter(
  Object var,
  JinjavaInterpreter interpreter,
  Object[] args,
  Map<String, Object> kwargs
) {
  long diff = parseDiffAmount(interpreter, args);
  ChronoUnit chronoUnit = parseChronoUnit(interpreter, args);

  if (var instanceof ZonedDateTime) {
    ZonedDateTime dateTime = (ZonedDateTime) var;
    return new PyishDate(dateTime.minus(diff, chronoUnit));
  } else if (var instanceof PyishDate) {
    PyishDate pyishDate = (PyishDate) var;
    return new PyishDate(pyishDate.toDateTime().minus(diff, chronoUnit));
  } else if (var instanceof Number) {
    Number timestamp = (Number) var;
    ZonedDateTime zonedDateTime = Functions.getDateTimeArg(timestamp, ZoneOffset.UTC);
    return new PyishDate(zonedDateTime.minus(diff, chronoUnit));
  }

  return var;
}
 
Example 10
Source File: RangeFilterTests.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "ZonedDateTimeRanges")
public void testRangeOfZonedDateTimes(ZonedDateTime start, ZonedDateTime end, Duration step, boolean parallel) {
    final boolean ascend = start.isBefore(end);
    final Range<ZonedDateTime> range = Range.of(start, end, step, v -> v.getHour() == 6);
    final Array<ZonedDateTime> array = range.toArray(parallel);
    final ZonedDateTime first = array.first(v -> true).map(ArrayValue::getValue).get();
    final ZonedDateTime last = array.last(v -> true).map(ArrayValue::getValue).get();
    Assert.assertEquals(array.typeCode(), ArrayType.ZONED_DATETIME);
    Assert.assertTrue(!array.style().isSparse());
    Assert.assertEquals(range.start(), start, "The range start");
    Assert.assertEquals(range.end(), end, "The range end");
    int index = 0;
    ZonedDateTime value = first;
    while (ascend ? value.isBefore(last) : value.isAfter(last)) {
        final ZonedDateTime actual = array.getValue(index);
        Assert.assertEquals(actual, value, "Value matches at " + index);
        Assert.assertTrue(ascend ? actual.compareTo(start) >= 0 && actual.isBefore(end) : actual.compareTo(start) <= 0 && actual.isAfter(end), "Value in bounds at " + index);
        value = ascend ? value.plus(step) : value.minus(step);
        while (value.getHour() == 6) value = ascend ? value.plus(step) : value.minus(step);
        index++;
    }
}
 
Example 11
Source File: BaseTick.java    From ta4j-origins with MIT License 5 votes vote down vote up
/**
 * Constructor.
 * @param timePeriod the time period
 * @param endTime the end time of the tick period
 * @param openPrice the open price of the tick period
 * @param highPrice the highest price of the tick period
 * @param lowPrice the lowest price of the tick period
 * @param closePrice the close price of the tick period
 * @param volume the volume of the tick period
 * @param amount the amount of the tick period
 */
public BaseTick(Duration timePeriod, ZonedDateTime endTime, Decimal openPrice, Decimal highPrice, Decimal lowPrice, Decimal closePrice, Decimal volume, Decimal amount) {
    checkTimeArguments(timePeriod, endTime);
    this.timePeriod = timePeriod;
    this.endTime = endTime;
    this.beginTime = endTime.minus(timePeriod);
    this.openPrice = openPrice;
    this.maxPrice = highPrice;
    this.minPrice = lowPrice;
    this.closePrice = closePrice;
    this.volume = volume;
    this.amount = amount;
}
 
Example 12
Source File: TestZonedDateTimeSerialization.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializationAsInt03NanosecondsWithoutTimeZone() throws Exception
{
    ZonedDateTime date = ZonedDateTime.now(Z3);
    date = date.minus(date.getNano(), ChronoUnit.NANOS);
    ObjectMapper mapper = newMapper();
    ZonedDateTime value = mapper.readerFor(ZonedDateTime.class)
            .with(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)
            .readValue(Long.toString(date.toEpochSecond()));
    assertIsEqual(date, value);
    assertEquals("The time zone is not correct.", DEFAULT_TZ, value.getZone());
}
 
Example 13
Source File: BaseTick.java    From ta4j-origins with MIT License 5 votes vote down vote up
/**
 * Constructor.
 * @param timePeriod the time period
 * @param endTime the end time of the tick period
 */
public BaseTick(Duration timePeriod, ZonedDateTime endTime) {
    checkTimeArguments(timePeriod, endTime);
    this.timePeriod = timePeriod;
    this.endTime = endTime;
    this.beginTime = endTime.minus(timePeriod);
}
 
Example 14
Source File: TestZonedDateTimeSerialization.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializationAsInt03NanosecondsWithTimeZone() throws Exception
{
    ZonedDateTime date = ZonedDateTime.now(Z3);
    date = date.minus(date.getNano(), ChronoUnit.NANOS);
    ObjectMapper mapper = newMapper(TimeZone.getDefault());
    ZonedDateTime value = mapper.readerFor(ZonedDateTime.class)
            .with(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)
            .readValue(Long.toString(date.toEpochSecond()));
    assertIsEqual(date, value);
    assertEquals("The time zone is not correct.", ZoneId.systemDefault(), value.getZone());
}
 
Example 15
Source File: Calendar.java    From calendar-component with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a date that is first day in the week that target given date belongs
 * to.
 *
 * @param date
 *            Target date
 * @return Date that is first date in same week that given date is.
 */

protected ZonedDateTime getFirstDayOfWeek(ZonedDateTime date) {

    DayOfWeek firstDayOfWeek = getFirstDayOfWeek();

    while (firstDayOfWeek != date.getDayOfWeek()) {
        date = date.minus(1, ChronoUnit.DAYS);
    }
    return date;
}
 
Example 16
Source File: Calendar.java    From calendar-component with Apache License 2.0 5 votes vote down vote up
/**
 * Get the day of week by the given calendar and its locale
 *
 * @param date
 *              Target date
 * @return The date corespond to the locale
 */
private ZonedDateTime getDayByLocale(ZonedDateTime date) {

    DayOfWeek firstDayOfWeek = getFirstDayOfWeek();
    int fow = date.getDayOfWeek().getValue();

    // sonday first ?
    if (firstDayOfWeek == SUNDAY && Duration.between(startDate, endDate).toDays() > 0) {
        return date.minus(1, ChronoUnit.DAYS);
    }

    return date;
}
 
Example 17
Source File: BlobStoreDeletedMessageVault.java    From james-project with Apache License 2.0 4 votes vote down vote up
ZonedDateTime getBeginningOfRetentionPeriod() {
    ZonedDateTime now = ZonedDateTime.now(clock);
    return now.minus(retentionConfiguration.getRetentionPeriod());
}
 
Example 18
Source File: MaintenanceScheduleHelper.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Calculate the next available maintenance window.
 *
 * @param cronSchedule
 *            is a cron expression with 6 mandatory fields and 1 last
 *            optional field: "second minute hour dayofmonth month weekday
 *            year".
 * @param duration
 *            in HH:mm:ss format specifying the duration of a maintenance
 *            window, for example 00:30:00 for 30 minutes.
 * @param timezone
 *            is the time zone specified as +/-hh:mm offset from UTC. For
 *            example +02:00 for CET summer time and +00:00 for UTC. The
 *            start time of a maintenance window calculated based on the
 *            cron expression is relative to this time zone.
 *
 * @return { @link Optional<ZonedDateTime>} of the next available window. In
 *         case there is none, or there are maintenance window validation
 *         errors, returns empty value.
 * 
 */
// Exception squid:S1166 - if there are validation error(format of cron
// expression or duration is wrong), we simply return empty value
@SuppressWarnings("squid:S1166")
public static Optional<ZonedDateTime> getNextMaintenanceWindow(final String cronSchedule, final String duration,
        final String timezone) {
    try {
        final ExecutionTime scheduleExecutor = ExecutionTime.forCron(getCronFromExpression(cronSchedule));
        final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.of(timezone));
        final ZonedDateTime after = now.minus(convertToISODuration(duration));
        final ZonedDateTime next = scheduleExecutor.nextExecution(after);
        return Optional.of(next);
    } catch (final RuntimeException ignored) {
        return Optional.empty();
    }
}
 
Example 19
Source File: BasicBackwardHandler.java    From calendar-component with Apache License 2.0 4 votes vote down vote up
@Override
public void backward(CalendarComponentEvents.BackwardEvent event) {

    int firstDay = event.getComponent().getFirstVisibleDayOfWeek();
    int lastDay = event.getComponent().getLastVisibleDayOfWeek();

    ZonedDateTime start = event.getComponent().getStartDate();
    ZonedDateTime end = event.getComponent().getEndDate();

    long durationInDays;

    // for week view durationInDays = 7, for day view durationInDays = 1
    if (event.getComponent().isDayMode()) { // day view
        durationInDays = 1;
    } else if (event.getComponent().isWeeklyMode()) {
        durationInDays = 7;
    } else {
        durationInDays = Duration.between(start, end).toDays() +1;
    }

    start = start.minus(durationInDays, ChronoUnit.DAYS);
    end = end.minus(durationInDays, ChronoUnit.DAYS);

    if (event.getComponent().isDayMode()) { // day view

        int dayOfWeek = start.get(ChronoField.DAY_OF_WEEK);

        ZonedDateTime newDate = start;
        while (!(firstDay <= dayOfWeek && dayOfWeek <= lastDay)) {

            newDate = newDate.minus(1, ChronoUnit.DAYS);

            dayOfWeek = newDate.get(ChronoField.DAY_OF_WEEK);
        }

        setDates(event, newDate, newDate);

        return;

    }

    if (durationInDays < 28) {
        setDates(event, start, end);
    } else {
        // go 7 days before and get the last day from month
        setDates(event, start.minus(7, ChronoUnit.DAYS).with(lastDayOfMonth()), end.with(lastDayOfMonth()));
    }
}
 
Example 20
Source File: createReportIT.java    From vind with Apache License 2.0 3 votes vote down vote up
@Test
@Ignore //only used for documentation
public void testReportAPI() {

    //configure at least appId and connection (in this case elastic search)

    final ElasticSearchReportConfiguration config = new ElasticSearchReportConfiguration()
            .setApplicationId("myApp")
            .setConnectionConfiguration(new ElasticSearchConnectionConfiguration(
                    "1.1.1.1",
                    "1920",
                    "logstash-2018.*"
            ));

    //create service with config and timerange

    ZonedDateTime to = ZonedDateTime.now();
    ZonedDateTime from = to.minus(1, ChronoUnit.WEEKS);

    ReportService service = new ElasticSearchReportService(config, from, to);

    //create report and serialize as HTML

    Report report = service.generateReport();

    new HtmlReportWriter().write(report, "/tmp/myreport.html");


}