Example usage for java.time LocalDate minusDays

List of usage examples for java.time LocalDate minusDays

Introduction

In this page you can find the example usage for java.time LocalDate minusDays.

Prototype

public LocalDate minusDays(long daysToSubtract) 

Source Link

Document

Returns a copy of this LocalDate with the specified number of days subtracted.

Usage

From source file:Main.java

public static void main(String[] args) {
    LocalDate a = LocalDate.of(2014, 6, 30);
    LocalDate b = a.minusDays(6);
    System.out.println(b);//  w  w  w  .  ja  va  2s. co  m
}

From source file:Main.java

public static void main(String... args) {
    LocalDate today = LocalDate.now();
    LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
    LocalDate yesterday = tomorrow.minusDays(2);

    System.out.println(today);/*  w  w w  .  j a v a 2  s.c o  m*/
    System.out.println(tomorrow);
    System.out.println(yesterday);

}

From source file:Main.java

public static void main(String[] args) {
    LocalDate today = LocalDate.now();

    // plus and minus operations
    System.out.println("10 days after today will be " + today.plusDays(10));
    System.out.println("3 weeks after today will be " + today.plusWeeks(3));
    System.out.println("20 months after today will be " + today.plusMonths(20));

    System.out.println("10 days before today will be " + today.minusDays(10));
    System.out.println("3 weeks before today will be " + today.minusWeeks(3));
    System.out.println("20 months before today will be " + today.minusMonths(20));

}

From source file:Main.java

public static LocalDate[] getWeekday(LocalDate date) {
    int DAYS_OF_WEEK = 7;

    if (date == null) {
        date = LocalDate.now();/* ww w. j a  v  a2s  .  c  o m*/
    }

    LocalDate begin = null;
    if (date.getDayOfWeek().equals(DayOfWeek.SUNDAY)) {
        begin = date;
    } else {
        begin = date.minusDays(date.getDayOfWeek().getValue());
    }
    LocalDate end = begin.plusDays(DAYS_OF_WEEK - 1);

    LocalDate localDate[] = { begin, end };

    return localDate;

}

From source file:com.romeikat.datamessie.core.statistics.app.shared.LocalStatisticsManager.java

@Override
public StatisticsDto getStatistics(final long projectId, final Integer numberOfDays) {
    final StatisticsDto dto = new StatisticsDto();

    final HibernateSessionProvider sessionProvider = new HibernateSessionProvider(sessionFactory);
    final Collection<Long> sourceIds = sourceDao.getIds(sessionProvider.getStatelessSession(), projectId,
            (Boolean) null);//from ww w .  j a  va  2  s .  c  o m

    LocalDate to;
    LocalDate from;
    to = LocalDate.now();
    from = to.minusDays(ObjectUtils.defaultIfNull(numberOfDays, 0) - 1);

    final Function<LocalDate, LocalDate> transformDateFunction = Functions.identity();

    final StatisticsSparseTable baseStatistics = getBaseStatistics(sessionProvider.getStatelessSession(),
            sourceIds, from, to);

    // All documents
    DocumentProcessingState[] states = DocumentProcessingState
            .getWithout(DocumentProcessingState.TECHNICAL_ERROR, DocumentProcessingState.TO_BE_DELETED);
    GetNumberOfDocumentsFunction getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(states);
    final SparseSingleTable<Long, LocalDate, Long> allDocumentsStatistics = statisticsService.getStatistics(
            baseStatistics, sourceIds, from, to, transformDateFunction, getNumberOfDocumentsFunction);
    final Function<Pair<Long, Long>, Long> mergeFunction = new Function<Pair<Long, Long>, Long>() {
        @Override
        public Long apply(final Pair<Long, Long> from) {
            return from.getLeft() + from.getRight();
        }
    };
    final Long allDocuments = allDocumentsStatistics.mergeAllValues(mergeFunction);
    dto.setAllDocuments(allDocuments);

    // Downloaded documents
    states = DocumentProcessingState.getWithout(DocumentProcessingState.DOWNLOAD_ERROR,
            DocumentProcessingState.REDIRECTING_ERROR, DocumentProcessingState.TECHNICAL_ERROR);
    getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(states);
    final SparseSingleTable<Long, LocalDate, Long> downloadedDocumentsStatistics = statisticsService
            .getStatistics(baseStatistics, sourceIds, from, to, transformDateFunction,
                    getNumberOfDocumentsFunction);
    final Long downloadedDocuments = downloadedDocumentsStatistics.mergeAllValues(mergeFunction);
    dto.setDownloadedDocuments(downloadedDocuments);

    // Preprocessed documents
    getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(
            DocumentProcessingState.getWith(DocumentProcessingState.STEMMED));
    final SparseSingleTable<Long, LocalDate, Long> preprocessedDocumentsStatistics = statisticsService
            .getStatistics(baseStatistics, sourceIds, from, to, transformDateFunction,
                    getNumberOfDocumentsFunction);
    final Long preprocessedDocuments = preprocessedDocumentsStatistics.mergeAllValues(mergeFunction);
    dto.setPreprocessedDocuments(preprocessedDocuments);

    // Download success
    final Double downloadSuccess;
    if (downloadedDocuments == null || allDocuments == null || allDocuments == 0) {
        downloadSuccess = null;
    } else {
        downloadSuccess = (double) downloadedDocuments / (double) allDocuments;
    }
    dto.setDownloadSuccess(downloadSuccess);

    // Preprocessing success
    getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(
            DocumentProcessingState.getWith(DocumentProcessingState.CLEANED,
                    DocumentProcessingState.CLEANING_ERROR, DocumentProcessingState.STEMMED));
    final SparseSingleTable<Long, LocalDate, Long> preprocessingAttemtedDocumentsStatistics = statisticsService
            .getStatistics(baseStatistics, sourceIds, from, to, transformDateFunction,
                    getNumberOfDocumentsFunction);
    final Long preprocessingAttemtedDocuments = preprocessingAttemtedDocumentsStatistics
            .mergeAllValues(mergeFunction);

    final Double preprocessingSuccess;
    if (preprocessedDocuments == null || preprocessingAttemtedDocuments == null
            || preprocessingAttemtedDocuments == 0) {
        preprocessingSuccess = null;
    } else {
        preprocessingSuccess = (double) preprocessedDocuments / (double) preprocessingAttemtedDocuments;
    }
    dto.setPreprocessingSuccess(preprocessingSuccess);

    // Documents to be preprocessed
    getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(
            DocumentProcessingState.getWith(DocumentProcessingState.DOWNLOADED,
                    DocumentProcessingState.REDIRECTED, DocumentProcessingState.CLEANED));
    final SparseSingleTable<Long, LocalDate, Long> documentsToBePreprocessedStatistics = statisticsService
            .getStatistics(baseStatistics, sourceIds, from, to, transformDateFunction,
                    getNumberOfDocumentsFunction);
    final Long documentsToBePreprocessed = documentsToBePreprocessedStatistics.mergeAllValues(mergeFunction);
    dto.setDocumentsToBePreprocessed(documentsToBePreprocessed);

    // Done
    sessionProvider.closeStatelessSession();
    return dto;
}

From source file:com.romeikat.datamessie.core.base.ui.page.StatisticsPage.java

private LocalDate getFromDate() {
    final LocalDate toDate = getToDate();
    if (toDate == null) {
        return LocalDate.now();
    }/*from ww  w.j  a  v a2 s. com*/

    Integer statisticsPeriod = DataMessieSession.get().getStatisticsPeriodModel().getObject();
    if (statisticsPeriod == null) {
        return LocalDate.now();
    }

    final StatisticsInterval statisticsInterval = DataMessieSession.get().getStatisticsIntervalModel()
            .getObject();
    if (statisticsInterval == null) {
        return LocalDate.now();
    }

    // Minimum value is 1
    statisticsPeriod = Math.max(statisticsPeriod, 1);

    // Calculate
    final LocalDate fromDate = toDate.plusDays(1);
    switch (statisticsInterval) {
    case DAY:
        return fromDate.minusDays(statisticsPeriod);
    case WEEK:
        return fromDate.minusWeeks(statisticsPeriod);
    case MONTH:
        return fromDate.minusMonths(statisticsPeriod);
    case YEAR:
        return fromDate.minusYears(statisticsPeriod);
    default:
        return LocalDate.now();
    }
}

From source file:nu.yona.server.analysis.service.ActivityServiceTest.java

private LocalDate getWeekStartDate(LocalDate date) {
    switch (date.getDayOfWeek()) {
    case SUNDAY://from w  w w.j a v a2 s.  c o m
        return date;
    default:
        return date.minusDays(date.getDayOfWeek().getValue());
    }
}

From source file:de.jfachwert.rechnung.Rechnungsmonat.java

/**
 * Diese Methode kann verwendet werden, um den letzten Freitag im Monat
 * zu bestimmen. Dazu ruft man diese Methode einfach mit
 * {@link DayOfWeek#FRIDAY} als Parameter auf.
 *
 * @param wochentag z.B. {@link DayOfWeek#FRIDAY}
 * @return z.B. letzter Arbeitstag// w ww  .jav  a 2s  . com
 * @since 0.6
 */
public LocalDate letzterTag(DayOfWeek wochentag) {
    LocalDate tag = ersterTag();
    while (tag.getDayOfWeek() != wochentag) {
        tag = tag.minusDays(1);
    }
    return tag;
}

From source file:org.wallride.service.PostService.java

/**
 *
 * @param blogLanguage//from   w  ww . j  a  va  2  s .c  o m
 * @param type
 * @param maxRank
 * @see PostService#getPopularPosts(String, PopularPost.Type)
 */
@CacheEvict(value = WallRideCacheConfiguration.POPULAR_POST_CACHE, key = "'list.type.' + #blogLanguage.language + '.' + #type")
public void updatePopularPosts(BlogLanguage blogLanguage, PopularPost.Type type, int maxRank) {
    logger.info("Start update of the popular posts");

    GoogleAnalytics googleAnalytics = blogLanguage.getBlog().getGoogleAnalytics();
    if (googleAnalytics == null) {
        logger.info("Configuration of Google Analytics can not be found");
        return;
    }

    Analytics analytics = GoogleAnalyticsUtils.buildClient(googleAnalytics);

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        logger.info("GuestServlet is not ready yet");
        return;
    }

    final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);

    Map<Post, Long> posts = new LinkedHashMap<>();

    int startIndex = 1;
    int currentRetry = 0;
    int totalResults = 0;

    do {
        try {
            LocalDate now = LocalDate.now();
            LocalDate startDate;
            switch (type) {
            case DAILY:
                startDate = now.minusDays(1);
                break;
            case WEEKLY:
                startDate = now.minusWeeks(1);
                break;
            case MONTHLY:
                startDate = now.minusMonths(1);
                break;
            default:
                throw new ServiceException();
            }

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Analytics.Data.Ga.Get get = analytics.data().ga()
                    .get(googleAnalytics.getProfileId(), startDate.format(dateTimeFormatter),
                            now.format(dateTimeFormatter), "ga:sessions")
                    .setDimensions(String.format("ga:pagePath", googleAnalytics.getCustomDimensionIndex()))
                    .setSort(String.format("-ga:sessions", googleAnalytics.getCustomDimensionIndex()))
                    .setStartIndex(startIndex).setMaxResults(GoogleAnalyticsUtils.MAX_RESULTS);
            if (blogLanguage.getBlog().isMultiLanguage()) {
                get.setFilters("ga:pagePath=~/" + blogLanguage.getLanguage() + "/");
            }

            logger.info(get.toString());
            final GaData gaData = get.execute();
            if (CollectionUtils.isEmpty(gaData.getRows())) {
                break;
            }

            for (List row : gaData.getRows()) {
                UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) row.get(0)).build();

                MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
                request.setRequestURI(uriComponents.getPath());
                request.setQueryString(uriComponents.getQuery());
                MockHttpServletResponse response = new MockHttpServletResponse();

                BlogLanguageRewriteRule rewriteRule = new BlogLanguageRewriteRule(blogService);
                BlogLanguageRewriteMatch rewriteMatch = (BlogLanguageRewriteMatch) rewriteRule.matches(request,
                        response);
                try {
                    rewriteMatch.execute(request, response);
                } catch (ServletException e) {
                    throw new ServiceException(e);
                } catch (IOException e) {
                    throw new ServiceException(e);
                }

                request.setRequestURI(rewriteMatch.getMatchingUrl());

                HandlerExecutionChain handler;
                try {
                    handler = mapping.getHandler(request);
                } catch (Exception e) {
                    throw new ServiceException(e);
                }

                if (!(handler.getHandler() instanceof HandlerMethod)) {
                    continue;
                }

                HandlerMethod method = (HandlerMethod) handler.getHandler();
                if (!method.getBeanType().equals(ArticleDescribeController.class)
                        && !method.getBeanType().equals(PageDescribeController.class)) {
                    continue;
                }

                // Last path mean code of post
                String code = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size() - 1);
                Post post = postRepository.findOneByCodeAndLanguage(code,
                        rewriteMatch.getBlogLanguage().getLanguage());
                if (post == null) {
                    logger.debug("Post not found [{}]", code);
                    continue;
                }

                if (!posts.containsKey(post)) {
                    posts.put(post, Long.parseLong((String) row.get(1)));
                }
                if (posts.size() >= maxRank) {
                    break;
                }
            }

            if (posts.size() >= maxRank) {
                break;
            }

            startIndex += GoogleAnalyticsUtils.MAX_RESULTS;
            totalResults = gaData.getTotalResults();
        } catch (IOException e) {
            logger.warn("Failed to synchronize with Google Analytics", e);
            if (currentRetry >= GoogleAnalyticsUtils.MAX_RETRY) {
                throw new GoogleAnalyticsException(e);
            }

            currentRetry++;
            logger.info("{} ms to sleep...", GoogleAnalyticsUtils.RETRY_INTERVAL);
            try {
                Thread.sleep(GoogleAnalyticsUtils.RETRY_INTERVAL);
            } catch (InterruptedException ie) {
                throw new GoogleAnalyticsException(e);
            }
            logger.info("Retry for the {} time", currentRetry);
        }
    } while (startIndex <= totalResults);

    popularPostRepository.deleteByType(blogLanguage.getLanguage(), type);

    int rank = 1;
    for (Map.Entry<Post, Long> entry : posts.entrySet()) {
        PopularPost popularPost = new PopularPost();
        popularPost.setLanguage(blogLanguage.getLanguage());
        popularPost.setType(type);
        popularPost.setRank(rank);
        popularPost.setViews(entry.getValue());
        popularPost.setPost(entry.getKey());
        popularPostRepository.saveAndFlush(popularPost);
        rank++;
    }

    logger.info("Complete the update of popular posts");
}

From source file:de.jfachwert.rechnung.Rechnungsmonat.java

/**
 * Diese Methode liefert den letzten Arbeitstag eines Monats. Allerdings
 * werden dabei keine Feiertag beruecksichtigt, sondern nur die Wochenende,
 * die auf einen letzten des Monats fallen, werden berucksichtigt.
 *
 * @return letzter Arbeitstag// w w  w.j av  a2s. c om
 * @since 0.6
 */
public LocalDate letzterArbeitstag() {
    LocalDate tag = letzterTag();
    switch (tag.getDayOfWeek()) {
    case SATURDAY:
        return tag.minusDays(1);
    case SUNDAY:
        return tag.minusDays(2);
    default:
        return tag;
    }
}