Example usage for org.apache.commons.lang3.time DateUtils truncate

List of usage examples for org.apache.commons.lang3.time DateUtils truncate

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils truncate.

Prototype

public static Date truncate(final Object date, final int field) 

Source Link

Document

Truncates a date, leaving the field specified as the most significant field.

For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you passed with HOUR, it would return 28 Mar 2002 13:00:00.000.

Usage

From source file:gr.abiss.calipso.model.dto.ReportDataSet.java

protected void initDefaults(Date dateFrom, Date dateTo, TimeUnit timeUnit, Map<String, Integer> keyIndexes,
        Map<String, Number> defaultDataEntry) {
    // init default record values, to be used in missing date slots to ensure regular records
    if (defaultDataEntry == null) {
        defaultDataEntry = new HashMap<String, Number>();
        for (String key : keyIndexes.keySet()) {
            defaultDataEntry.put(key, new Integer(0));
        }/*  www. j  a va 2s  .c o m*/
    }

    // init default values for all dates in range to ensure regular records
    Calendar start = Calendar.getInstance();
    // get start of day
    start.setTime(DateUtils.truncate(dateFrom, Calendar.DATE));
    Calendar end = Calendar.getInstance();
    // get end of day
    end.setTime(DateUtils.addMilliseconds(DateUtils.ceiling(dateTo, Calendar.DATE), -1));
    for (Date date = start.getTime(); start.before(end); start.add(timeUnit.toCalendarUnit(),
            1), date = start.getTime()) {
        this.addEntry(date, defaultDataEntry);
    }
}

From source file:com.mgmtp.jfunk.common.random.MathRandom.java

/**
 * Returns a random date in the range of [min, max].
 * /*from   ww w . ja v a2  s .c  o  m*/
 * @param min
 *            minimum value for generated date (in milliseconds)
 * @param max
 *            maximum value for generated date (in milliseconds)
 */
public Date getDate(final long min, final long max) {
    long millis = getLong(min, max);
    return DateUtils.truncate(new Date(millis), Calendar.DATE);
}

From source file:io.lavagna.web.api.MilestoneController.java

@ExpectPermission(Permission.READ)
@RequestMapping(value = "/api/project/{projectShortName}/cards-by-milestone-detail/{milestoneId}", method = RequestMethod.GET)
public MilestoneDetail findCardsByMilestoneDetail(@PathVariable("projectShortName") String projectShortName,
        @PathVariable("milestoneId") int milestoneId, UserWithPermission user) {

    int projectId = projectService.findIdByShortName(projectShortName);
    LabelListValueWithMetadata ms = cardLabelRepository.findListValueById(milestoneId);
    if (ms == null) {
        throw new IllegalArgumentException("Milestone not found");
    }//  w  w  w.  j  ava 2 s .  co m

    SearchFilter filter = filter(SearchFilter.FilterType.MILESTONE, SearchFilter.ValueType.STRING,
            ms.getValue());
    List<MilestoneCount> mcs = statisticsService.findCardsCountByMilestone(projectId, ms.getId());
    Map<Long, Pair<Long, Long>> assignedAndClosedCards = statisticsService.getAssignedAndClosedCardsByMilestone(
            ms, DateUtils.addWeeks(DateUtils.truncate(new Date(), Calendar.DATE), -2));

    SearchFilter notTrashFilter = filter(SearchFilter.FilterType.NOTLOCATION, SearchFilter.ValueType.STRING,
            BoardColumn.BoardColumnLocation.TRASH.toString());

    SearchResults cards = searchService.find(Arrays.asList(filter, notTrashFilter), projectId, null, user);

    Map<ColumnDefinition, Long> cardsCountByStatus = new HashMap<>();
    for (MilestoneCount count : mcs) {
        cardsCountByStatus.put(count.getColumnDefinition(), count.getCount());
    }

    return new MilestoneDetail(cardsCountByStatus, getStatusColors(projectId), cards, assignedAndClosedCards);
}

From source file:com.webbfontaine.valuewebb.action.pricedb.pdss.PdssCriteriaContainer.java

public static Criterion transformAgeOfPriceToPriceDate(UserCriterion ageOfPriceCriterion,
        UserCriterion criterionToModify) throws Exception {

    Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
    long userInputedDaysAmount = (Long) ageOfPriceCriterion.getValue();
    Date todayMinusUserInputedDaysAmount = DateUtils.addDays(today, -(int) userInputedDaysAmount);
    criterionToModify.setValue(todayMinusUserInputedDaysAmount);

    String ageOfPriceCriterionCondition = ageOfPriceCriterion.getCondition();
    switch (ageOfPriceCriterionCondition) {
    case StringConditions.GE:
        criterionToModify.setCondition(StringConditions.LE);
        break;//from  w w w  .ja  v a  2s . com
    case StringConditions.LE:
        criterionToModify.setCondition(StringConditions.GE);
        break;
    case StringConditions.GT:
        criterionToModify.setCondition(StringConditions.LT);
        break;
    case StringConditions.LT:
        criterionToModify.setCondition(StringConditions.GT);
        break;
    default:
        criterionToModify.setCondition(ageOfPriceCriterionCondition);
        break;
    }

    return criterionToModify.transform();
}

From source file:com.inkubator.hrm.service.impl.SchedulerConfigServiceImpl.java

@Override //Harus serialiasai agar tidak tumpang tindih dengan proses schedulerr yang berjalan
@Transactional(readOnly = false, isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void update(SchedulerConfig entity) throws Exception {
    long totalDuplicate = schedulerConfigDao.getTotalByNameAndNotId(entity.getName(), entity.getId());
    if (totalDuplicate > 0) {
        throw new BussinessException("scheduler_config.error_name");
    }//from   www . j ava2 s .  c o  m
    SchedulerConfig schedulerConfig = schedulerConfigDao.getEntiyByPK(entity.getId());
    schedulerConfig.setDateStartExecution(entity.getDateStartExecution());
    schedulerConfig.setEndDate(entity.getEndDate());
    schedulerConfig.setIsTimeDiv(entity.getIsTimeDiv());
    //        schedulerConfig.setLastExecution(entity.getLastExecution());
    schedulerConfig.setName(entity.getName());
    schedulerConfig.setRepeateNumber(entity.getRepeateNumber());
    schedulerConfig.setRepeateType(entity.getRepeateType());
    schedulerConfig.setSchedullerTime(entity.getSchedullerTime());
    schedulerConfig.setSchedullerType(entity.getSchedullerType());
    schedulerConfig.setStartDate(entity.getStartDate());
    schedulerConfig.setHourDiv(entity.getHourDiv());
    schedulerConfig.setMinuteDiv(entity.getMinuteDiv());
    schedulerConfig.setUpdatedBy(UserInfoUtil.getUserName());
    schedulerConfig.setUpdatedOn(new Date());
    schedulerConfig.setIsActive(entity.getIsActive());
    if (entity.getIsTimeDiv()) {
        Date now = new Date();
        String nowString = new SimpleDateFormat("dd MM yyyy HH:mm").format(now);
        //            schedulerConfig.setLastExecution(new SimpleDateFormat("dd MM yyyy HH:mm").parse(nowString));
        schedulerConfig.setLastExecution(DateUtils.truncate(now, Calendar.MINUTE));
    }
    schedulerConfigDao.update(schedulerConfig);
}

From source file:io.lavagna.service.StatisticsServiceTest.java

private void verifyResults(Map<Long, Map<ColumnDefinition, Long>> results, int resultsSize, Date date,
        ColumnDefinition def, long expectedValue) {
    Assert.assertEquals(resultsSize, results.size());
    long dateTime = DateUtils.truncate(date, Calendar.DATE).getTime();
    if (!results.containsKey(dateTime)) {
        Assert.fail();//w  w w .  j a va  2s .co m
    }

    Map<ColumnDefinition, Long> day = results.get(dateTime);
    if (!day.containsKey(def)) {
        Assert.fail();
    }

    Assert.assertEquals(expectedValue, day.get(def).longValue());
}

From source file:com.mgmtp.jfunk.common.random.MathRandom.java

private Calendar createCalendar(final long millis) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(millis);/* www . j a  v a 2  s.  c  o m*/
    return DateUtils.truncate(cal, Calendar.DATE);
}

From source file:de.tor.tribes.types.TimeSpan.java

/**
 * @return the date/*from  ww w.j a v  a  2s . c o  m*/
 */
public Date getDate() {
    if (isValidAtSpecificDay()) {
        return DateUtils.truncate(new Date(exactSpan.getMinimum()), Calendar.DATE);
    }
    return null;
}

From source file:gov.va.isaac.gui.preferences.plugins.ViewCoordinatePreferencesPluginView.java

public static Date getStartOfDay(Date date) {
    return DateUtils.truncate(date, Calendar.DATE);
}

From source file:eu.ggnet.dwoss.redtape.reporting.RedTapeCloserOperation.java

/**
 * The closing selects and closes all dossiers and documents in a closable state. This includes production of appropriated values for report.
 * <p/>/*from   ww  w. j  av  a2s .  co  m*/
 * The workflow:
 * <ol>
 * <li>Load all open {@link Dossiers}, and filter them by the closing states of the associated {@link Documents}.See
 * {@link #findReportable(de.dw.progress.IMonitor)}</li>
 * <li>Filter out all Document, which have {@link StockUnit}'s on open {@link StockTransaction}.</li>
 * <li>Create the resulting {@link ReportLine}'s and persist them in the report database. See
 * {@link #poluteReporting(java.util.Set, java.util.Date, de.dw.progress.IMonitor)} </li>
 * <li>Close the selected {@link Dossier}'s and {@link Document}'s in redTape. See {@link #closeRedTape(java.util.Set, de.dw.progress.IMonitor)}</li>
 * <li>Find all associated {@link StockUnit}'s and roll them out. See
 * {@link #closeStock(java.util.Set, java.lang.String, java.lang.String, de.dw.progress.IMonitor)}</li>
 * </ol>
 * <p>
 * <p/>
 * @param arranger the arranger
 * @param manual   is this called manual or automatic
 */
private void closeing(String arranger, boolean manual) {
    Date now = new Date();
    String msg = (manual ? "Manueller" : "Automatischer") + " (Tages)abschluss vom "
            + DateFormats.ISO.format(now) + " ausgefhrt durch " + arranger;
    L.info("closing:{}", msg);
    SubMonitor m = monitorFactory.newSubMonitor((manual ? "Manueller" : "Automatischer") + " (Tages)abschluss",
            100);
    m.start();

    L.info("closing:week persisted");
    Set<Document> reportable = findReportable(m.newChild(30));
    L.info("closing:documents selected");
    reportable = filterOpenStockTransactions(reportable, m.newChild(5));
    L.info("closing:documents filtered");

    poluteReporting(reportable, DateUtils.truncate(new Date(), Calendar.DATE), m.newChild(15));
    L.info("closing:repoting poluted");

    closeRedTape(reportable, m.newChild(10));
    L.info("closed:redTape:reportables");

    closeRedTape(findCloseableBlocker(), m.newChild(10));
    L.info("closed:redTape:nonreportables");

    closeStock(reportable.stream().map(Document::getDossier).map(Dossier::getId).collect(Collectors.toSet()),
            "Rollout by " + (manual ? "manuel" : "automatic") + " closing on " + DateFormats.ISO.format(now),
            arranger, m);
    L.info("closed:stock");

    m.finish();
}