Example usage for java.time LocalDateTime truncatedTo

List of usage examples for java.time LocalDateTime truncatedTo

Introduction

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

Prototype

public LocalDateTime truncatedTo(TemporalUnit unit) 

Source Link

Document

Returns a copy of this LocalDateTime with the time truncated.

Usage

From source file:Main.java

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

    LocalDateTime t = a.truncatedTo(ChronoUnit.HOURS);

    System.out.println(t);/*from w  w  w.ja  va 2  s.c o  m*/
}

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

private DayActivity mockExistingActivities(Goal forGoal, Activity... activities) {
    LocalDateTime startTime = activities[0].getStartTime();
    DayActivity dayActivity = DayActivity.createInstance(userAnonEntity, forGoal, userAnonZoneId,
            startTime.truncatedTo(ChronoUnit.DAYS).toLocalDate());
    Arrays.asList(activities).forEach(a -> dayActivity.addActivity(a));
    ActivityDto existingActivity = ActivityDto.createInstance(activities[activities.length - 1]);
    when(mockDayActivityRepository.findOne(userAnonId, dayActivity.getStartDate(), forGoal.getId()))
            .thenReturn(dayActivity);/*from ww w .  ja va  2s .c om*/
    when(mockAnalysisEngineCacheService.fetchLastActivityForUser(userAnonId, deviceAnonId, forGoal.getId()))
            .thenReturn(existingActivity);
    WeekActivity weekActivity = WeekActivity.createInstance(userAnonEntity, forGoal, userAnonZoneId,
            TimeUtil.getStartOfWeek(startTime.toLocalDate()));
    weekActivity.addDayActivity(dayActivity);
    forGoal.addWeekActivity(weekActivity);
    return dayActivity;
}

From source file:edu.usu.sdl.openstorefront.service.UserServiceImpl.java

@Override
public void cleanupOldUserMessages() {
    int maxDays = Convert.toInteger(PropertiesManager.getValue(PropertiesManager.KEY_MESSAGE_KEEP_DAYS, "30"));

    LocalDateTime archiveTime = LocalDateTime.now();
    archiveTime = archiveTime.minusDays(maxDays);
    archiveTime = archiveTime.truncatedTo(ChronoUnit.DAYS);
    String deleteQuery = "updateDts < :maxUpdateDts AND activeStatus = :activeStatusParam";

    ZonedDateTime zdt = archiveTime.atZone(ZoneId.systemDefault());
    Date archiveDts = Date.from(zdt.toInstant());

    Map<String, Object> queryParams = new HashMap<>();
    queryParams.put("maxUpdateDts", archiveDts);
    queryParams.put("activeStatusParam", UserMessage.INACTIVE_STATUS);

    persistenceService.deleteByQuery(UserMessage.class, deleteQuery, queryParams);
}

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

@CacheEvict(value = WallRideCacheConfiguration.PAGE_CACHE, allEntries = true)
public Page savePage(PageUpdateRequest request, AuthorizedUser authorizedUser) {
    postRepository.lock(request.getId());
    Page page = pageRepository.findOneByIdAndLanguage(request.getId(), request.getLanguage());
    LocalDateTime now = LocalDateTime.now();

    String code = request.getCode();
    if (code == null) {
        try {/*from w  ww . j  av  a 2s .c  om*/
            code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale());
        } catch (ParseException e) {
            throw new ServiceException(e);
        }
    }
    if (!StringUtils.hasText(code)) {
        if (!page.getStatus().equals(Post.Status.DRAFT)) {
            throw new EmptyCodeException();
        }
    }
    if (!page.getStatus().equals(Post.Status.DRAFT)) {
        Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage());
        if (duplicate != null && !duplicate.equals(page)) {
            throw new DuplicateCodeException(code);
        }
    }

    if (!page.getStatus().equals(Post.Status.DRAFT)) {
        page.setCode(code);
        page.setDraftedCode(null);
    } else {
        page.setCode(null);
        page.setDraftedCode(code);
    }

    Page parent = (request.getParentId() != null)
            ? entityManager.getReference(Page.class, request.getParentId())
            : null;
    if (!(page.getParent() == null && parent == null)
            && !ObjectUtils.nullSafeEquals(page.getParent(), parent)) {
        pageRepository.shiftLftRgt(page.getLft(), page.getRgt());
        pageRepository.shiftRgt(page.getRgt());
        pageRepository.shiftLft(page.getRgt());

        int rgt = 0;
        if (parent == null) {
            rgt = pageRepository.findMaxRgt();
            rgt++;
        } else {
            rgt = parent.getRgt();
            pageRepository.unshiftRgt(rgt);
            pageRepository.unshiftLft(rgt);
        }
        page.setLft(rgt);
        page.setRgt(rgt + 1);
    }

    page.setParent(parent);

    Media cover = null;
    if (request.getCoverId() != null) {
        cover = entityManager.getReference(Media.class, request.getCoverId());
    }
    page.setCover(cover);
    page.setTitle(request.getTitle());
    page.setBody(request.getBody());

    //      User author = null;
    //      if (request.getAuthorId() != null) {
    //         author = entityManager.getReference(User.class, request.getAuthorId());
    //      }
    //      page.setAuthor(author);

    LocalDateTime date = request.getDate();
    if (Post.Status.PUBLISHED.equals(page.getStatus())) {
        if (date == null) {
            date = now.truncatedTo(ChronoUnit.HOURS);
        } else if (date.isAfter(now)) {
            page.setStatus(Post.Status.SCHEDULED);
        }
    }
    page.setDate(date);
    page.setLanguage(request.getLanguage());

    page.getCategories().clear();
    SortedSet<Category> categories = new TreeSet<>();
    for (long categoryId : request.getCategoryIds()) {
        categories.add(entityManager.getReference(Category.class, categoryId));
    }
    page.setCategories(categories);

    page.getTags().clear();
    Set<String> tagNames = StringUtils.commaDelimitedListToSet(request.getTags());
    if (!CollectionUtils.isEmpty(tagNames)) {
        for (String tagName : tagNames) {
            Tag tag = tagRepository.findOneForUpdateByNameAndLanguage(tagName, request.getLanguage());
            if (tag == null) {
                tag = new Tag();
                tag.setName(tagName);
                tag.setLanguage(request.getLanguage());
                page.setCreatedAt(now);
                page.setCreatedBy(authorizedUser.toString());
                page.setUpdatedAt(now);
                page.setUpdatedBy(authorizedUser.toString());
                tag = tagRepository.saveAndFlush(tag);
            }
            page.getTags().add(tag);
        }
    }

    page.getRelatedPosts().clear();
    Set<Post> relatedPosts = new HashSet<>();
    for (long relatedId : request.getRelatedPostIds()) {
        relatedPosts.add(entityManager.getReference(Post.class, relatedId));
    }
    page.setRelatedToPosts(relatedPosts);

    Seo seo = new Seo();
    seo.setTitle(request.getSeoTitle());
    seo.setDescription(request.getSeoDescription());
    seo.setKeywords(request.getSeoKeywords());
    page.setSeo(seo);

    List<Media> medias = new ArrayList<>();
    if (StringUtils.hasText(request.getBody())) {
        //         Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String mediaUrlPrefix = wallRideProperties.getMediaUrlPrefix();
        Pattern mediaUrlPattern = Pattern.compile(String.format("%s([0-9a-zA-Z\\-]+)", mediaUrlPrefix));
        Matcher mediaUrlMatcher = mediaUrlPattern.matcher(request.getBody());
        while (mediaUrlMatcher.find()) {
            Media media = mediaRepository.findOneById(mediaUrlMatcher.group(1));
            medias.add(media);
        }
    }
    page.setMedias(medias);

    page.setUpdatedAt(now);
    page.setUpdatedBy(authorizedUser.toString());

    SortedSet<CustomFieldValue> fieldValues = new TreeSet<>();
    Map<CustomField, CustomFieldValue> valueMap = new LinkedHashMap<>();
    for (CustomFieldValue value : page.getCustomFieldValues()) {
        valueMap.put(value.getCustomField(), value);
    }

    page.getCustomFieldValues().clear();
    if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) {
        for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) {
            CustomField customField = entityManager.getReference(CustomField.class,
                    valueForm.getCustomFieldId());
            CustomFieldValue value = valueMap.get(customField);
            if (value == null) {
                value = new CustomFieldValue();
            }
            value.setCustomField(customField);
            value.setPost(page);
            if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)) {
                if (!ArrayUtils.isEmpty(valueForm.getTextValues())) {
                    value.setTextValue(String.join(",", valueForm.getTextValues()));
                } else {
                    value.setTextValue(null);
                }
            } else {
                value.setTextValue(valueForm.getTextValue());
            }
            value.setStringValue(valueForm.getStringValue());
            value.setNumberValue(valueForm.getNumberValue());
            value.setDateValue(valueForm.getDateValue());
            value.setDatetimeValue(valueForm.getDatetimeValue());
            if (!value.isEmpty()) {
                fieldValues.add(value);
            }
        }
    }
    page.setCustomFieldValues(fieldValues);

    return pageRepository.save(page);
}

From source file:onl.area51.gfs.grib2.job.GribRetriever.java

/**
 * Convert a {@link LocalDateTime} to a GFS run time. Specifically this is the date and hour of the day restricted to 0, 7, 12 or 18 hours.
 * <p>//from  w  w  w.  jav  a2  s .  c o m
 * @param date date
 * <p>
 * @return date modified to the nearest GFS run (earlier than date) or null if date was null
 */
public static LocalDateTime toGFSRunTime(LocalDateTime date) {
    if (date == null) {
        return null;
    }

    LocalDateTime dateTime = date.truncatedTo(ChronoUnit.HOURS);

    // Only allow hours 0, 6, 12 & 18
    int h = dateTime.get(ChronoField.HOUR_OF_DAY);
    if (h % 6 == 0) {
        return dateTime;
    }

    return dateTime.withHour((h / 6) * 6);
}