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

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

Introduction

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

Prototype

public static Date truncate(Object date, int field) 

Source Link

Document

Truncate this date, leaving the field specified as the most significant field.

For example, if you had the datetime 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:es.indaba.jdbc.test.InterceptorTest.java

@Test
public void dateTest() throws Exception {
    Date testVal = new Date();
    TestBean testService = BeanProvider.getContextualReference(TestBean.class, false);
    ProcedureResult<Date> result = testService.callEchoDateAsFunction(testVal);
    assertNotNull(result);//from w w w  . ja v  a2  s .  com
    assertEquals(DateUtils.truncate(testVal, Calendar.DAY_OF_MONTH),
            DateUtils.truncate(result.getValue(), Calendar.DAY_OF_MONTH));

    result = testService.callEchoDateAsProcedure(testVal);
    assertNotNull(result);
    assertEquals(DateUtils.truncate(testVal, Calendar.DAY_OF_MONTH),
            DateUtils.truncate(result.getValue(), Calendar.DAY_OF_MONTH));
}

From source file:br.com.gerenciapessoal.repository.Lancamentos.java

@SuppressWarnings("UnusedAssignment")
public Map<Date, BigDecimal> valoresTotaisPorData(Integer numeroDeDias, Conta conta) {
    Session session = manager.unwrap(Session.class);

    Calendar dataInicial = Calendar.getInstance();
    dataInicial = DateUtils.truncate(dataInicial, Calendar.DAY_OF_MONTH);
    dataInicial.add(Calendar.DAY_OF_MONTH, numeroDeDias * -1);

    Map<Date, BigDecimal> resultado = criarMapaVazio(numeroDeDias, dataInicial);

    Criteria criteria = session.createCriteria(Lancamento.class).createAlias("conta", "c");

    criteria.setProjection(Projections.projectionList()
            .add(Projections.sqlGroupProjection("date(data_emissao) as data", "date(data_emissao)",
                    new String[] { "data" }, new Type[] { StandardBasicTypes.DATE }))
            .add(Projections.sum("valorLanca").as("valor")))
            .add(Restrictions.ge("dataEmissao", dataInicial.getTime()));

    if (conta != null) {
        criteria.add(Restrictions.eq("c.id", conta.getId()));
    }// w w  w  .  jav  a  2 s  .  c  om
    List<DataValor> valoresPorData = criteria.setResultTransformer(Transformers.aliasToBean(DataValor.class))
            .list();

    for (DataValor dataValor : valoresPorData) {
        resultado.put(dataValor.getData(), dataValor.getValor());
    }

    return resultado;
}

From source file:net.sf.housekeeper.domain.Food.java

/**
 * Sets the expiry date of this item to one second before midnight of the
 * given date. A value of null specifies that the expiry for this item
 * should not be set to a value./*from  w  w  w .j a  v  a2  s  .com*/
 * 
 * @param expiry The new expiry date or null to unset the date.
 */
public void setExpiry(final Date expiry) {
    if (expiry != null) {
        final Date truncatedExpiry = DateUtils.truncate(expiry, Calendar.DAY_OF_MONTH);
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(truncatedExpiry);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        this.expiry = calendar.getTime();
    } else {
        this.expiry = null;
    }
}

From source file:com.epam.catgenome.helper.EntityHelper.java

public static Reference createReference() {
    final Reference reference = new Reference();
    reference.setSize(REF_BASES_COUNT);/*from  w  ww . j  ava2s.c o  m*/
    reference.setName("Test.Reference.0.0.1");
    reference.setPath("/contents/tests/references/" + reference.getId());
    reference.setCreatedDate(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH));
    reference.setCreatedBy(AuthUtils.getCurrentUserId());
    reference.setType(BiologicalDataItemResourceType.FILE);
    reference.setIndex(
            createIndex(BiologicalDataItemFormat.REFERENCE_INDEX, BiologicalDataItemResourceType.FILE, ""));
    final String[] dictionary = new String[] { "A1", "A2", "X" };
    for (String name : dictionary) {
        final Chromosome chromosome = new Chromosome(name, CHROMOSOME_LENGTH);
        chromosome
                .setPath(String.format("/references/%s/chromosomes/%s/sequences.nib", reference.getId(), name));
        reference.getChromosomes().add(chromosome);
    }
    return reference;
}

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

/**
 * {@inheritDoc}/*  w  ww  .  j ava  2  s  . co m*/
 */
@Override
public Date getCurrentTradingDate(final long exchangeId, final Date dateTime) {

    Validate.notNull(dateTime, "Data time is null");

    Exchange exchange = this.exchangeDao.get(exchangeId);
    Validate.notNull(exchange, "exchange not found");

    Date date = DateUtils.addDays(DateUtils.truncate(dateTime, Calendar.DATE), 2);
    NavigableSet<Date> openTimes = new TreeSet<>();
    while ((openTimes.floor(dateTime)) == null) {
        date = DateUtils.addDays(date, -1);
        openTimes.addAll(getOpenTimes(exchange, date));
    }
    return date;

}

From source file:gov.utah.dts.det.ccl.model.FacilityTest.java

@Test
public void testGetActiveExemptions() {
    Date now = DateUtils.truncate(new Date(), Calendar.DATE);
    Facility f1 = new Facility();

    //an empty list should be returned when there are no exemptions
    assertTrue(f1.getActiveExemptions().isEmpty());

    Exemption e1 = new Exemption();
    e1.setStartDate(DateUtils.addDays(now, -60));
    e1.setExpirationDate(DateUtils.addDays(now, -30));
    f1.addExemption(e1);//  w  w w .  j a  v  a 2  s.  c  om
    assertTrue(f1.getActiveLicenses().isEmpty());

    Exemption e2 = new Exemption();
    e2.setStartDate(DateUtils.addDays(now, -30));
    e2.setExpirationDate(DateUtils.addDays(now, 30));
    f1.addExemption(e2);
    assertTrue(f1.getActiveExemptions().size() == 1);
    assertEquals(f1.getActiveExemptions().get(0), e2);
}

From source file:gsn.vsensor.AbstractScheduledVirtualSensor.java

/**
 * Called once while initializing an instance of the virtual sensor
 * Gets schedule parameters from VSD, calculates timer parameters and instantiates timer instance.
 * //from ww  w .j  av a2s .  co m
 * @return True if the initialization is done successfully.
 */
public boolean initialize() {
    TreeMap<String, String> params = getVirtualSensorConfiguration().getMainClassInitialParams();
    String rate_value = params.get(RATE_PARAM);

    if (rate_value == null) {
        logger.warn("Parameter \"" + RATE_PARAM + "\" not provider in Virtual Sensor file");
        return false;
    }

    clock_rate = Integer.parseInt(rate_value);

    String start_value = params.get(START_PARAM);

    if (start_value != null) { //start value set in VSD
        try {
            startTime = Helpers.convertTimeFromIsoToLong(start_value);
        } catch (Exception e) {
            logger.error(
                    "Failed to parse the start-time parameter of the remote wrapper, a sample time could be:"
                            + (CURRENT_TIME));
            throw new RuntimeException(e);
        }
    }
    // If the scheduled start is not in the future
    // then start at the next whole time interval
    if (System.currentTimeMillis() >= startTime) {
        startTime = System.currentTimeMillis(); // current time
        // Calculate from midnight   
        long midnight = DateUtils.truncate(new Date(), Calendar.DATE).getTime();
        long current_time = System.currentTimeMillis();
        // Start
        startTime = midnight + (((current_time - midnight) / clock_rate) + 1) * clock_rate;
    } //otherwise use the time retrieved from the VSD

    logger.warn(getVirtualSensorConfiguration().getName() + " scheduled to start at "
            + new Date(startTime).toString());

    // startTime is used in the virtual sensor class to start a timer
    timer0 = new Timer();
    // timer task is started in the sub class
    return true;
}

From source file:net.duckling.ddl.service.browselog.impl.BrowseLogServiceImpl.java

public List<BrowseStat> getTopPageView(int tid, int length, int daysAgo) {
    Date now = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
    Date dateOfDaysAgo = DateUtils.addDays(now, -daysAgo);
    return historyDao.getTopPageView(tid, length, dateOfDaysAgo);
}

From source file:com.haulmont.timesheets.gui.approve.BulkTimeEntriesApprove.java

@Override
public void init(Map<String, Object> params) {
    super.init(params);

    if (securityAssistant.isSuperUser()) {
        timeEntriesDs.setQuery("select e from ts$TimeEntry e "
                + "where e.date >= :component$dateFrom and e.date <= :component$dateTo");
    }//  w  ww.  j a  va  2s .  c  om

    timeEntriesTable.getColumn("overtime")
            .setAggregation(ComponentsHelper.createAggregationInfo(
                    projectsService.getEntityMetaPropertyPath(TimeEntry.class, "overtime"),
                    new TimeEntryOvertimeAggregation()));

    timeEntriesDs.addCollectionChangeListener(e -> {
        Multimap<Map<String, Object>, TimeEntry> map = ArrayListMultimap.create();
        for (TimeEntry item : timeEntriesDs.getItems()) {
            Map<String, Object> key = new TreeMap<>();
            key.put("user", item.getUser());
            key.put("date", item.getDate());
            map.put(key, item);
        }

        for (Map.Entry<Map<String, Object>, Collection<TimeEntry>> entry : map.asMap().entrySet()) {
            BigDecimal thisDaysSummary = BigDecimal.ZERO;
            for (TimeEntry timeEntry : entry.getValue()) {
                thisDaysSummary = thisDaysSummary.add(timeEntry.getTimeInHours());
            }

            for (TimeEntry timeEntry : entry.getValue()) {
                BigDecimal planHoursForDay = workdaysTools.isWorkday(timeEntry.getDate())
                        ? workTimeConfigBean.getWorkHourForDay()
                        : BigDecimal.ZERO;
                BigDecimal overtime = thisDaysSummary.subtract(planHoursForDay);
                timeEntry.setOvertimeInHours(overtime);
            }
        }
    });

    Date previousMonth = DateUtils.addMonths(timeSource.currentTimestamp(), -1);
    dateFrom.setValue(DateUtils.truncate(previousMonth, Calendar.MONTH));
    dateTo.setValue(DateUtils.addDays(DateUtils.truncate(timeSource.currentTimestamp(), Calendar.MONTH), -1));

    approve.addAction(new AbstractAction("approveAll") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesDs.getItems(), TimeEntryStatus.APPROVED);
        }
    });

    approve.addAction(new AbstractAction("approveSelected") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.APPROVED);
        }
    });

    reject.addAction(new AbstractAction("rejectAll") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesDs.getItems(), TimeEntryStatus.REJECTED);
        }
    });

    reject.addAction(new AbstractAction("rejectSelected") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.REJECTED);
        }
    });

    status.setOptionsList(Arrays.asList(TimeEntryStatus.values()));
    user.setOptionsList(
            projectsService.getManagedUsers(userSession.getCurrentOrSubstitutedUser(), View.MINIMAL));
}

From source file:br.com.nordestefomento.jrimum.utilix.BancoUtil.java

/**
 * <p>/* ww w  . j  av a2  s .c o  m*/
 * Calcula o fator de vencimento a partir da subtrao entre a DATA DE
 * VENCIMENTO de um ttulo e a DATA BASE fixada em 07/10/1997.
 * </p>
 * 
 * <p>
 * O fator de vencimento nada mais  que um referencial numrico de 4
 * dgitos que representa a quantidade de dias decorridos desde a data base
 * (07/10/1997) at a data de vencimento do ttulo. Ou seja, a diferena em
 * dias entre duas datas.
 * </p>
 * 
 * <p>
 * Exemplos:
 * </p>
 * <ul type="circule"> <li>07/10/1997 (Fator = 0);</li> <li>03/07/2000
 * (Fator = 1000);</li> <li>05/07/2000 (Fator = 1002);</li> <li>01/05/2002
 * (Fator = 1667);</li> <li>21/02/2025 (Fator = 9999).</li> </ul>
 * 
 * <p>
 * Funcionamento:
 * </p>
 * 
 * <ul type="square"> <li>Caso a data de vencimento seja anterior a data
 * base (Teoricamente fator negativo), uma exceo do tipo
 * IllegalArgumentException ser lanada.</li> <li>A data limite para o
 * clculo do fator de vencimento  21/02/2025 (Fator de vencimento = 9999).
 * Caso a data de vencimento seja posterior a data limite, uma exceo do
 * tipo IllegalArgumentException ser lanada.</li> </ul>
 * 
 * <p>
 * <strong>ATENO</strong>, esse clculo se refere a ttulos em cobrana,
 * ou melhor: BOLETOS. Desta forma, lembramos que a DATA BASE  uma norma da
 * FEBRABAN. Essa norma diz que todos os boletos emitidos a partir de 1 de
 * setembro de 2000 (primeiro dia til = 03/07/2000 - SEGUNDA) devem seguir
 * esta regra de clculo para compor a informao de vencimento no cdigo de
 * barras. Portanto, boletos no padro FEBRABAN quando capturados por
 * sistemas da rede bancria permitem que se possa realizar a operao
 * inversa, ou seja, adicionar  data base o fator de vencimento capturado.
 * Obtendo ento a data de vencimento deste boleto.
 * </p>
 * 
 * @param dataVencimento
 *            data de vencimento de um ttulo
 * @return fator de vencimento calculado
 * @throws IllegalArgumentException
 * 
 * @since 0.2
 */

public static int calculceFatorDeVencimento(Date dataVencimento) throws IllegalArgumentException {

    Date dataVencTruncada = null;
    int fator;

    if (isNull(dataVencimento)) {
        throw new IllegalArgumentException(
                "Impossvel realizar o clculo do fator" + " de vencimento de uma data nula.");
    } else {
        dataVencTruncada = DateUtils.truncate(dataVencimento, Calendar.DATE);
        if (dataVencTruncada.before(DATA_BASE_DO_FATOR_DE_VENCIMENTO)
                || dataVencTruncada.after(DATA_LIMITE_DO_FATOR_DE_VENCIMENTO)) {
            throw new IllegalArgumentException(
                    "Para o clculo do fator de" + " vencimento se faz necessrio informar uma data entre"
                            + " " + DateUtil.FORMAT_DD_MM_YYYY.format(DATA_BASE_DO_FATOR_DE_VENCIMENTO) + " e "
                            + DateUtil.FORMAT_DD_MM_YYYY.format(DATA_LIMITE_DO_FATOR_DE_VENCIMENTO));
        } else {
            fator = (int) DateUtil.calculeDiferencaEmDias(DATA_BASE_DO_FATOR_DE_VENCIMENTO, dataVencTruncada);
        }
    }

    return fator;
}