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:org.openbravo.test.accounting.RecordID2Test.java

/**
 * Verifies documents can be posted and unposted and that affects fact_acct (RecordID2 and
 * DateBalanced) Case 4: Invoice posted , payment posted and reconciliation posted. After both are
 * posted receivables entry should be balanced. Invoice: I/3 Payment: 400002 Reconciliation:
 * 1000034. When Payment and reconciliation are posted in transit account balance should be 0
 *///from   w w w.  j a  v  a2  s . c o m
@Test
public void testRecordID2_case5() {
    // Invoice I/3 from QA dataset
    String strCInvoiceId = "FF8080813282F9FE0132830158E20024";
    String strCAcctSchemaId = "9A68A0F8D72D4580B3EC3CAA00A5E1F0";

    OBContext.setAdminMode(true);
    try {
        Invoice invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strRecordID2 = invoice.getFINPaymentScheduleList().get(0).getId();
        assertEquals("Invoice Not Posted", "Y", invoice.getPosted());
        ResetAccounting.delete(invoice.getClient().getId(), invoice.getOrganization().getId(), "318",
                invoice.getId(), "", "");
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        String strReceivablesAccountId = getReceivablesAccount(invoice.getBusinessPartner(), strCAcctSchemaId);
        assertEquals("Invoice Could Not Be Unposted", "N", invoice.getPosted());
        assertTrue("RecordID2 not updated after unposting invoice", BigDecimal.ZERO.compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        postDocument(strCInvoiceId, "318", invoice.getClient().getId(), invoice.getOrganization().getId());
        invoice = OBDal.getInstance().get(Invoice.class, strCInvoiceId);
        assertTrue("RecordID2 not updated after posting invoice", new BigDecimal("100").compareTo(
                getBalance(strRecordID2, TABLE_INVOICE, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        assertEquals("Invoice Could Not be Posted", "Y", invoice.getPosted());

        // Payment: 400002 - 02-04-2011 - Customer A - 100.00 from QA Dataset. Paying previous invoice
        String strFINPaymentId = "FF8080813282F9FE013283022F3E0030";
        FIN_Payment payment = OBDal.getInstance().get(FIN_Payment.class, strFINPaymentId);
        String strInTransitAccountId = getInTransitAccount(payment.getAccount(), strCAcctSchemaId);
        String strRecordID2InTransit = payment.getId();
        assertEquals("Payment Not Posted", "Y", payment.getPosted());
        ResetAccounting.delete(payment.getClient().getId(), payment.getOrganization().getId(), TABLE_PAYMENT,
                payment.getId(), "", "");
        payment = OBDal.getInstance().get(FIN_Payment.class, strFINPaymentId);
        assertEquals("Payment Could Not Be Unposted", "N", payment.getPosted());
        assertTrue("RecordID2 for receivables not updated after unposting Payment", BigDecimal.ZERO.compareTo(
                getBalance(strRecordID2, TABLE_PAYMENT, strCAcctSchemaId, strReceivablesAccountId)) == 0);
        assertTrue("RecordID2 for In Transit not updated after unposting Payment",
                BigDecimal.ZERO.compareTo(getBalance(strRecordID2InTransit, TABLE_PAYMENT, strCAcctSchemaId,
                        strInTransitAccountId)) == 0);
        postDocument(strFINPaymentId, TABLE_PAYMENT, payment.getClient().getId(),
                payment.getOrganization().getId());
        payment = OBDal.getInstance().get(FIN_Payment.class, strFINPaymentId);
        assertTrue("RecordID2 for receivables not updated after posting Payment",
                new BigDecimal("-100").compareTo(getBalance(strRecordID2, TABLE_PAYMENT, strCAcctSchemaId,
                        strReceivablesAccountId)) == 0);
        assertTrue("RecordID2 for In Transit not updated after posting Payment",
                new BigDecimal("100").compareTo(getBalance(strRecordID2InTransit, TABLE_PAYMENT,
                        strCAcctSchemaId, strInTransitAccountId)) == 0);
        assertEquals("Payment Could Not be Posted", "Y", payment.getPosted());
        assertEquals("Entry Not Balanced for Receivables",
                DateUtils.truncate(payment.getPaymentDate(), Calendar.DATE),
                getBalancedDate(strRecordID2, strReceivablesAccountId));
        FIN_FinaccTransaction transaction = payment.getFINFinaccTransactionList().get(0);
        FIN_Reconciliation reconciliation = transaction.getReconciliation();
        assertEquals("Reconciliation Not Posted", "Y", reconciliation.getPosted());
        ResetAccounting.delete(reconciliation.getClient().getId(), reconciliation.getOrganization().getId(),
                TABLE_RECONCILIATION, reconciliation.getId(), "", "");
        reconciliation = OBDal.getInstance().get(FIN_Reconciliation.class, reconciliation.getId());
        assertEquals("Reconciliation Could Not Be Unposted", "N", reconciliation.getPosted());
        assertTrue("RecordID2 for in transit not updated after unposting reconciliation",
                BigDecimal.ZERO.compareTo(getBalance(strRecordID2InTransit, TABLE_RECONCILIATION,
                        strCAcctSchemaId, strInTransitAccountId)) == 0);
        postDocument(reconciliation.getId(), TABLE_RECONCILIATION, reconciliation.getClient().getId(),
                reconciliation.getOrganization().getId());
        reconciliation = OBDal.getInstance().get(FIN_Reconciliation.class, reconciliation.getId());
        assertTrue("RecordID2 for in transit not updated after posting reconciliation",
                new BigDecimal("-100").compareTo(getBalance(strRecordID2InTransit, TABLE_RECONCILIATION,
                        strCAcctSchemaId, strInTransitAccountId)) == 0);
        assertEquals("Reconciliation Could Not be Posted", "Y", reconciliation.getPosted());
        assertEquals("Entry Not Balanced", DateUtils.truncate(transaction.getTransactionDate(), Calendar.DATE),
                getBalancedDate(strRecordID2InTransit, strInTransitAccountId));

    } catch (Exception e) {
        assertFalse(true);
        log.error("Error when executing query", e);
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.openkoala.koala.monitor.common.KoalaDateUtils.java

/**
 * ???<br>//from  ww w.  j a v a2  s  .c  o m
 * generate by: vakin jiang at 2012-5-21
 * 
 * @param date
 * @return
 */
public static Date getLastDateOfMonth(Date date) {
    return DateUtils.addDays(DateUtils.truncate(DateUtils.addMonths(date, 1), Calendar.MONTH), -1);
}

From source file:org.openmicroscopy.shoola.agents.metadata.editor.ChannelAcquisitionComponent.java

/**
 * Formats time into a more human readable format
 * // www . j  a v  a2s.co  m
 * @param tInS
 *            The time in seconds
 * @return See above.
 */
private String getReadableTime(double tInS) {
    if (tInS == 0.0)
        return "0 s";

    Calendar date = Calendar.getInstance();
    date = DateUtils.truncate(date, Calendar.YEAR);
    date.add(Calendar.MILLISECOND, (int) (tInS * 1000));

    int d, h, m, s;

    if (tInS > (23 * 60 * 60)) {
        date = DateUtils.round(date, Calendar.MINUTE);
        d = date.get(Calendar.DAY_OF_YEAR) - 1;
        h = date.get(Calendar.HOUR_OF_DAY);
        m = date.get(Calendar.MINUTE);
        return d + " d " + h + " h " + (m > 0 ? m + " min " : "");
    } else if (tInS > (59 * 60)) {
        date = DateUtils.round(date, Calendar.MINUTE);
        h = date.get(Calendar.HOUR_OF_DAY);
        m = date.get(Calendar.MINUTE);
        return h + " h " + m + " min";
    } else if (tInS > 59) {
        date = DateUtils.round(date, Calendar.SECOND);
        m = date.get(Calendar.MINUTE);
        s = date.get(Calendar.SECOND);
        return m + " min " + s + " s";
    } else if (tInS > 0.9)
        return sFormat.format(tInS);

    return msFormat.format(tInS * 1000);
}

From source file:org.openvpms.archetype.rules.finance.account.AccountType.java

/**
 * Calculates the overdue payment date based on the specified date.
 * This is <tt>date - paymentTerms * paymentUOM</tt>
 *
 * @param date the date//from  ww  w  .  java2 s  .c  om
 * @return the overdue date
 */
public Date getOverdueDate(Date date) {
    DateUnits payment = getPaymentUOM();
    if (payment != null) {
        date = DateUtils.truncate(date, Calendar.DATE); // strip any time
        int days = getPaymentTerms();
        return DateRules.getDate(date, -days, payment);
    }
    return date;
}

From source file:org.openvpms.archetype.rules.util.DateRules.java

/**
 * Returns the date part of a date-time, zero-ing out any time component.
 *
 * @param datetime the date/time. May be {@code null}
 * @return the date part of {@code datetime}, or {@code null} if {@code datetime} is null
 *//*w w w .  j ava2 s.  c o  m*/
public static Date getDate(Date datetime) {
    if (datetime == null) {
        return null;
    }
    return DateUtils.truncate(datetime, Calendar.DAY_OF_MONTH);
}

From source file:org.openvpms.archetype.rules.util.DateRules.java

/**
 * Helper to compare two dates.// ww w.  ja  v  a2  s  .  com
 * <p/>
 * This is functionally equivalent to the {@link Date#compareTo(Date)}
 * method, except that it doesn't throw {@code ClassCastExceptions}
 * if {@code lhs} is an instance of a {@link Timestamp Timestamp} and
 * {@code rhs} isn't.
 * <p/>
 * For timestamps, the nanoseconds are ignored.
 *
 * @param lhs          the date
 * @param rhs          the date to compare with
 * @param ignoreMillis if {@code true}, ignore milliseconds
 * @return {@code 0} if the {@code lhs} is equal to {@code rhs};
 *         a value less than {@code 0} if {@code lhs} is before
 *         {@code rhs}; and a value greater than
 *         {@code 0} if {@code lhs} is after {@code rhs}.
 */
public static int compareTo(Date lhs, Date rhs, boolean ignoreMillis) {
    if (ignoreMillis) {
        lhs = DateUtils.truncate(lhs, Calendar.SECOND);
        rhs = DateUtils.truncate(rhs, Calendar.SECOND);
    }
    return compareTo(lhs, rhs);
}

From source file:org.openvpms.archetype.rules.workflow.AppointmentQueryTestCase.java

/**
 * Helper to remove any seconds from a time, as the database may not
 * store them.//from  ww w . j  a v  a 2 s . c  om
 *
 * @param timestamp the timestamp
 * @return the timestamp with seconds and milliseconds removed
 */
private Date getTimestamp(Date timestamp) {
    return DateUtils.truncate(timestamp, Calendar.SECOND);
}

From source file:org.openvpms.archetype.util.DateRulesTestCase.java

/**
 * Tests the {@link DateRules#getToday()} method.
 *///from  ww w.ja v  a 2s.c o  m
@Test
public void testGetToday() {
    Date expected = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
    assertEquals(expected, DateRules.getToday());
}

From source file:org.openvpms.archetype.util.DateRulesTestCase.java

/**
 * Tests the {@link DateRules#getTomorrow()} method.
 */// w w  w.ja  va 2s  . co m
@Test
public void testGetTomorrow() {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(new Date());
    calendar.add(Calendar.DAY_OF_MONTH, 1);

    Date expected = DateUtils.truncate(calendar.getTime(), Calendar.DAY_OF_MONTH);
    assertEquals(expected, DateRules.getTomorrow());
}

From source file:org.oscarehr.managers.ScheduleManager.java

public DayWorkSchedule getDayWorkSchedule(String providerNo, Calendar date) {
    // algorithm/*from w ww  .  j a v a 2s .  com*/
    //----------
    // select entries from scheduledate for the given day/provider where status = 'A' (for active?)
    // "hour" setting is the template to apply, i.e. template name
    // select entry from scheduletemplate to get the template to apply for the given day
    // timecode is a breakdown of the day into equal slots, where _ means nothing and some letter means a code in scheduletemplatecode
    // The only way to know the duration of the time code is to divide it up, i.e. minutes_per_day/timecode.length, i.e. 1440 minutes per second / 96 length = 15 minutes per slot.
    // For each time slot, then look up the scheduletemplatecode

    DayWorkSchedule dayWorkSchedule = new DayWorkSchedule();

    ScheduleHoliday scheduleHoliday = scheduleHolidayDao.find(date.getTime());
    dayWorkSchedule.setHoliday(scheduleHoliday != null);

    ScheduleDate scheduleDate = scheduleDateDao.findByProviderNoAndDate(providerNo, date.getTime());
    if (scheduleDate == null) {
        logger.debug(
                "No scheduledate for date requested. providerNo=" + providerNo + ", date=" + date.getTime());
        return (null);
    }
    String scheduleTemplateName = scheduleDate.getHour();

    // okay this is a mess, the ScheduleTemplate is messed up because no one links there via a PK, they only link there via the name column
    // and the name column isn't unique... so... we will have to do a search for the right template.
    // first we'll check under the providersId, if not we'll check under the public id.
    ScheduleTemplatePrimaryKey scheduleTemplatePrimaryKey = new ScheduleTemplatePrimaryKey(providerNo,
            scheduleTemplateName);
    ScheduleTemplate scheduleTemplate = scheduleTemplateDao.find(scheduleTemplatePrimaryKey);
    if (scheduleTemplate == null) {
        scheduleTemplatePrimaryKey = new ScheduleTemplatePrimaryKey(
                ScheduleTemplatePrimaryKey.DODGY_FAKE_PROVIDER_NO_USED_TO_HOLD_PUBLIC_TEMPLATES,
                scheduleTemplateName);
        scheduleTemplate = scheduleTemplateDao.find(scheduleTemplatePrimaryKey);
    }

    //  if it's still null, then ignore it as there's no schedule for the day.
    if (scheduleTemplate != null) {
        // time interval
        String timecode = scheduleTemplate.getTimecode();
        int timeSlotDuration = (60 * 24) / timecode.length();
        dayWorkSchedule.setTimeSlotDurationMin(timeSlotDuration);

        // sort out designated timeslots and their purpose
        Calendar timeSlot = (Calendar) date.clone();

        //make sure the appts returned are in local time. 
        timeSlot.setTimeZone(Calendar.getInstance().getTimeZone());
        timeSlot = DateUtils.truncate(timeSlot, Calendar.DAY_OF_MONTH);
        TreeMap<Calendar, Character> allTimeSlots = dayWorkSchedule.getTimeSlots();

        for (int i = 0; i < timecode.length(); i++) {
            // ignore _ because that's a blank place holder identifier... also not my fault, just processing what's been already written.
            if ('_' != timecode.charAt(i)) {
                allTimeSlots.put((Calendar) timeSlot.clone(), timecode.charAt(i));
            }

            timeSlot.add(GregorianCalendar.MINUTE, timeSlotDuration);
        }
    }

    // This method will not log access as the schedule is not private medical data.
    return (dayWorkSchedule);
}