Example usage for java.time LocalDateTime plusDays

List of usage examples for java.time LocalDateTime plusDays

Introduction

In this page you can find the example usage for java.time LocalDateTime plusDays.

Prototype

public LocalDateTime plusDays(long days) 

Source Link

Document

Returns a copy of this LocalDateTime with the specified number of days added.

Usage

From source file:Main.java

public static void main(String[] args) {
    LocalDateTime a = LocalDateTime.of(2014, 6, 30, 12, 00);

    LocalDateTime t = a.plusDays(100);

    System.out.println(t);/*from   w  w  w  . j a v  a  2s .com*/
}

From source file:Main.java

/**
 * Checks if the type of the given date. Possible return values are standard
 * time, the date when to switch to daylight saving time (in Europe the last
 * Sunday in March), daylight saving time or the date when to switch back to
 * standard time (in Europe the last Sunday in October).
 * //from www  . j  av a2 s  .  co m
 * @return DayType
 * @param cal
 *          Date to check, cannot be null
 */
public static DayType getDSTType(LocalDate cal) {
    DayType status = DayType.DAYLIGHT_SAVING_TIME;
    LocalDateTime testDate = cal.atStartOfDay();
    ZonedDateTime zdt = ZonedDateTime.of(testDate, ZoneId.systemDefault());
    // Find type of day
    if (zdt.getZone().getRules().isDaylightSavings(testDate.toInstant(zdt.getOffset())))
        status = DayType.DAYLIGHT_SAVING_TIME;
    else
        status = DayType.STANDARD_TIME;
    // Check the day after
    testDate = testDate.plusDays(1);
    zdt = ZonedDateTime.of(testDate, ZoneId.systemDefault());
    // Find type of day after
    if (zdt.getZone().getRules().isDaylightSavings(testDate.toInstant(zdt.getOffset()))) {
        if (status != DayType.DAYLIGHT_SAVING_TIME)
            status = DayType.TO_DAYLIGHT_SAVING_TIME;
    } else {
        if (status == DayType.DAYLIGHT_SAVING_TIME)
            status = DayType.TO_STANDARD_TIME;
    }
    return status;
}

From source file:ch.algotrader.dao.marketData.TickDaoImpl.java

@Override
public List<Tick> findTicksBySecurityAndMinDate(int limit, long securityId, Date minDate, int intervalDays) {

    Validate.notNull(minDate, "minDate is null");

    LocalDateTime minLocalDateTime = DateTimeLegacy.toLocalDateTime(minDate);
    LocalDateTime maxLocalDateTime = minLocalDateTime.plusDays(intervalDays);
    return find("Tick.findTicksBySecurityAndMinDate", limit, QueryType.BY_NAME,
            new NamedParam("securityId", securityId),
            new NamedParam("minDate", DateTimeLegacy.toLocalDateTime(minLocalDateTime)),
            new NamedParam("maxDate", DateTimeLegacy.toLocalDateTime(maxLocalDateTime)));
}

From source file:org.thevortex.lighting.jinks.robot.Recurrence.java

/**
 * Get the next occurrence from a time.//  ww w . j ava2  s  .  c o  m
 *
 * @param fromWhen when
 * @return the next occurrence or {@code null} if there is no more
 */
public LocalDateTime nextOccurrence(TemporalAccessor fromWhen) {
    LocalDateTime from = LocalDateTime.from(fromWhen);

    // if it's not today, try the next day
    if (frequency == Frequency.WEEKLY && !days.contains(from.getDayOfWeek())) {
        return nextOccurrence(from.plusDays(1).truncatedTo(ChronoUnit.DAYS));
    }

    // if we've already started, it's too late - next day
    if (from.toLocalTime().isAfter(startTime)) {
        return nextOccurrence(from.plusDays(1).truncatedTo(ChronoUnit.DAYS));
    }

    // otherwise, we're on the right day, so just adjust the time
    return from.with(startTime).truncatedTo(ChronoUnit.MINUTES);
}

From source file:com.bdb.weather.display.day.DayXYPlotPane.java

/**
 * Update the domain axis of the plot to the day passed in. This can be used to change the plot
 * to show a different day/*  w  w  w. j ava  2  s. co  m*/
 * 
 * @param date The date
 */
private void updateDomainAxis(LocalDate date) {
    plot.clearRangeMarkers();

    LocalDateTime midnight = date.atStartOfDay();
    LocalDateTime endOfDay = midnight.plusDays(1).minusSeconds(1);

    dateAxis.setRange(TimeUtils.localDateTimeToDate(midnight), TimeUtils.localDateTimeToDate(endOfDay));
}

From source file:com.otway.picasasync.syncutil.SyncManager.java

public void BeginCompleteSync() {

    if (syncState.getIsInProgress()) {

        log.warn("Sync started when already in progress. Doing nothing...");
        return;/*  w w  w.j  a va 2 s .  co  m*/
    }

    LocalDateTime startDate = LocalDateTime.now();
    startDate = startDate.plusDays(-1 * settings.getSyncDateRange());
    boolean endedWithError = true;

    log.info("Synchronisation started. Max photo age: " + startDate);

    if (SwingUtilities.isEventDispatchThread()) {
        log.error("Sync started on GUI thread!");
        throw new RuntimeException("This method should not be run on the GUI thread");
    }

    try {
        syncState.start();

        File rootFolder = initFolder();

        syncState.setStatus("Starting synchronisation");

        // Do the actual sync
        Synchronise(rootFolder, startDate);

        syncState.setStatus("Sync complete");

        endedWithError = false;

    } catch (ServiceForbiddenException forbiddenEx) {

        log.error("Auth expired. Discarding web client; will re-auth on next loop.");
        invalidateWebClient();
    } catch (UnknownHostException ex) {
        log.warn("Unknown host exception. Did we lose internet access?");
        // Cancel this sync, and we'll try again in a bit
        syncState.setStatus("Error finding Google.com. Sync Aborted.");
    } catch (SocketException ex) {
        log.warn("Socket exception. Did we lose internet access?");
        // Cancel this sync, and we'll try again in a bit
        syncState.setStatus("Connection error. Sync Aborted.");
    } catch (SocketTimeoutException ex) {
        log.warn("Socket timeout. Did we lose internet access?");
        // Cancel this sync, and we'll try again in a bit
        syncState.setStatus("Connection timeout. Sync aborted.");
    } catch (Exception ex) {
        log.error("Unexpected error: ", ex);
    } finally {
        log.info("Synchronisation ended.");
        if (endedWithError)
            syncState.setStatus("Sync failed.");
        syncState.cancel(endedWithError);
    }
}

From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java

/**
 * Returns all events, that are taking place on a specified date. The date parameter needs to be formatted according to the following pattern: YYYY/MM/DD. This function is invoked by GETting the URI /api/admin/event/date
 * @param date The selected date, correctly formatted (YYYY/MM/DD)
 * @return An HTTP response with a status code. If the function succeeds, a list of events is returned, otherwise an error code is returned.
 *//*from   w ww  .  j  av a  2  s. c o  m*/
@RequestMapping(value = "date", produces = "application/json", method = RequestMethod.GET)
public ResponseEntity<List<Event>> getEventsOfDate(@RequestParam String date, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Getting events of date " + date);
    LocalDateTime startOfDay, endOfDay, startOfMonth, endOfMonth;
    ArrayList<Event> eventsOfDay = new ArrayList<>();
    try {
        // Get start of day and start of next day
        startOfDay = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE).atStartOfDay();
        endOfDay = startOfDay.plusDays(1);

        startOfMonth = LocalDate.of(startOfDay.getYear(), startOfDay.getMonth(), 1).atStartOfDay();
        endOfMonth = startOfMonth.plusMonths(1);
        logger.debug("[" + currentUser + "] Converted to date object: " + startOfDay.toString());
    } catch (DateTimeParseException e) {
        logger.warn("[" + currentUser + "] Unable to parse date: " + date + ": " + e.toString());
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    logger.debug("Getting all single day events...");
    eventsOfDay.addAll(eventRepository.findAllByStartDateTimeBetweenAndMultiDate(startOfDay, endOfDay, false));
    logger.debug("All single day events retrieved, got " + eventsOfDay.size() + " events so far");

    logger.debug("Getting all multi day events...");
    //Collecting all multi date events, that either start or end within the selected month (which means that events that are spanning over several months are not collected)
    eventsOfDay.addAll(Stream.concat(
            eventRepository.findAllByStartDateTimeBetweenAndMultiDate(startOfMonth, endOfMonth, true).stream(), //All multi date events starting within the month
            eventRepository.findAllByEndDateTimeBetweenAndMultiDate(startOfMonth, endOfMonth, true).stream()) //All multi date events ending within the month
            .distinct() //Removing all duplicated events
            .parallel()
            .filter(event -> event.getStartDate().isEqual(startOfDay.toLocalDate())
                    || event.getEndDate().isEqual(startOfDay.toLocalDate())
                    || (event.getEndDate().isAfter(endOfDay.toLocalDate())
                            && event.getStartDate().isBefore(startOfDay.toLocalDate()))) //Filter all multi date events that do not span over the date
            .collect(Collectors.toList()));
    logger.debug("All multi day events gathered, got " + eventsOfDay.size() + " events so far");

    if (eventsOfDay.isEmpty()) {
        logger.warn("[" + currentUser + "] The events list of " + date + " is empty");
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
        eventsOfDay.replaceAll(Event::getSendingObjectOnlyNameTimeId);
        logger.debug("[" + currentUser + "] Returning " + eventsOfDay.size() + " events for " + date);
        return new ResponseEntity<>(eventsOfDay, HttpStatus.OK);
    }
}

From source file:ch.algotrader.service.LookupServiceImpl.java

private List<Tick> getTicksByMinDate(final int limit, final long securityId, final Date minDate,
        int intervalDays) {

    Validate.notNull(minDate, "Min date is null");

    LocalDateTime minLocalDateTime = DateTimeLegacy.toLocalDateTime(minDate);
    LocalDateTime maxLocalDateTime = minLocalDateTime.plusDays(intervalDays);
    return this.genericDao.find(Tick.class, "Tick.findTicksBySecurityAndMinDate", limit, QueryType.BY_NAME,
            new NamedParam("securityId", securityId),
            new NamedParam("minDate", DateTimeLegacy.toLocalDateTime(minLocalDateTime)),
            new NamedParam("maxDate", DateTimeLegacy.toLocalDateTime(maxLocalDateTime)));
}

From source file:tech.tablesaw.filters.SearchPerformanceTest.java

public static void main(String[] args) throws Exception {

    Stopwatch stopwatch = Stopwatch.createStarted();

    Table t = defineSchema();/*from ww w . j  a v a  2 s .  c  o  m*/

    generateTestData(t, numberOfRecordsInTable, stopwatch);
    t = t.sortAscendingOn("date");

    dateIndex = new LongIndex(t.dateTimeColumn("date"));
    t.setName("Observations");

    DateTimeColumn dates = t.dateTimeColumn("date");
    DoubleColumn lowValues = t.doubleColumn("lowValue");
    DoubleColumn highValues = t.doubleColumn("highValue");

    System.out.println(dates.summary());
    System.out.println(lowValues.summary());
    System.out.println(highValues.summary());

    LocalDateTime testDateTime = LocalDate.of(2010, 1, 1).atStartOfDay();
    double testLowValue = 500;
    double testHighValue = 999_500;

    stopwatch.reset();
    stopwatch.start();

    int count = 0;
    for (int i = 0; i < 1000; i++) {
        testDateTime = testDateTime.plusDays(2);
        int rowNumber = getRowNumber(t, testDateTime, testLowValue, testHighValue);
        if (rowNumber >= 0) {
            count++;
        }
    }

    stopwatch.stop();
    System.out.println("using rows with an index. found " + count + " in "
            + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
}

From source file:xyz.codevomit.bootlog.BootlogBootstrapper.java

private void saveDatabaseEntryFor(File file, int index) {
    try {/*from  ww w. j a  v  a2 s. com*/
        LocalDateTime conventionalDate = LocalDateTime.of(2016, 1, 1, 0, 0);
        String url = file.getName().replace(".md", "");
        Post post = Post.builder().editedOn(conventionalDate).publishedOn(conventionalDate.plusDays(index))
                .sourceUrl(url).title("The Title of " + url).build();
        postService.createPostWithText(post, FileUtils.readFileToString(file));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}