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

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

Introduction

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

Prototype

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

Source Link

Document

Rounds 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 this was passed with HOUR, it would return 28 Mar 2002 14:00:00.000.

Usage

From source file:org.kuali.coeus.common.committee.impl.bo.CommitteeScheduleBase.java

public Timestamp getStartTime() {
    if (startTime == null || startTime.getTime() == 0) {
        java.util.Date dt = new java.util.Date(0);
        dt = DateUtils.round(dt, Calendar.DAY_OF_MONTH);
        if (viewStartTime != null) {
            dt = DateUtils.addMinutes(dt, viewStartTime.findMinutes());
            // dt = DateUtils.addMinutes(dt, getViewTime().findMinutes());
        }/*from   w  w w  .  ja v a  2s.co m*/
        this.startTime = new Timestamp(dt.getTime());
    }

    return startTime;
}

From source file:org.kuali.coeus.common.committee.impl.bo.CommitteeScheduleBase.java

public Timestamp getEndTime() {
    if (endTime == null || endTime.getTime() == 0) {
        java.util.Date dt = new java.util.Date(0); // set to 1969/12/31 19:00 ?
        dt = DateUtils.round(dt, Calendar.DAY_OF_MONTH); // force it to 1970-01-01
        if (viewEndTime != null) {
            dt = DateUtils.addMinutes(dt, viewEndTime.findMinutes());
            // dt = DateUtils.addMinutes(dt, getViewTime().findMinutes());
        }/*from   w w  w.j a  va2  s  .c o m*/
        this.endTime = new Timestamp(dt.getTime());
    }
    return endTime;
}

From source file:org.kuali.coeus.common.committee.impl.meeting.MeetingServiceImplBase.java

protected Timestamp addHrMinToDate(Time12HrFmt viewTime) {
    java.util.Date dt = new java.util.Date(0); // this is actually 12-31-1969 19:00.  its GMT time
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy h:mm a");
    try {//w w  w  .j a v  a  2s  . c o  m
        // support localization. 
        dt = dateFormat.parse("01/01/1970 " + viewTime.getTime() + " " + viewTime.getMeridiem());
        return new Timestamp(dt.getTime());
    } catch (Exception e) {
        // TODO : not sure to throw runtimeexception or not.
        // folowing may convert date to 07-02-1970 iftz is gmt+12 or more
        dt = DateUtils.round(dt, Calendar.DAY_OF_MONTH);
        return new Timestamp(DateUtils.addMinutes(dt, viewTime.findMinutes()).getTime());

    }
}

From source file:org.kuali.coeus.common.committee.impl.service.impl.CommitteeScheduleServiceImplBase.java

/**
 * Helper method to convert date and minutes into Time24HrFmt object.
 * @param date/*w  w  w  .java2s.com*/
 * @param min
 * @return
 * @throws ParseException
 */
protected Time24HrFmt getTime24hFmt(Date date, int min) throws ParseException {
    Date dt = DateUtils.round(date, Calendar.DAY_OF_MONTH);
    dt = DateUtils.addMinutes(dt, min);
    Calendar cl = new GregorianCalendar();
    cl.setTime(dt);
    StringBuffer sb = new StringBuffer();
    String str = sb.append(cl.get(Calendar.HOUR_OF_DAY)).append(COLON).append(cl.get(Calendar.MINUTE))
            .toString();
    return new Time24HrFmt(str);
}

From source file:org.kuali.kra.committee.bo.CommitteeScheduleTest.java

@Override
protected void boPrerequisite() {
    super.boPrerequisite();
    java.util.Date dt = new java.util.Date(0);
    Time12HrFmt time12HrFmt = new Time12HrFmt("10:30", MERIDIEM.AM);
    dt = DateUtils.round(dt, Calendar.DAY_OF_MONTH);
    dt = DateUtils.addMinutes(dt, time12HrFmt.findMinutes());
    FIELD_TIME_VALUE = new java.sql.Timestamp(dt.getTime());
}

From source file:org.structr.web.servlet.HtmlServlet.java

private static boolean notModifiedSince(final HttpServletRequest request, HttpServletResponse response,
        final AbstractNode node, final boolean dontCache) {

    boolean notModified = false;
    final Date lastModified = node.getLastModifiedDate();

    // add some caching directives to header
    // see http://weblogs.java.net/blog/2007/08/08/expires-http-header-magic-number-yslow
    final DateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    response.setHeader("Date", httpDateFormat.format(new Date()));

    final Calendar cal = new GregorianCalendar();
    final Integer seconds = node.getProperty(Page.cacheForSeconds);

    if (!dontCache && seconds != null) {

        cal.add(Calendar.SECOND, seconds);
        response.setHeader("Cache-Control", "max-age=" + seconds + ", s-maxage=" + seconds + "");
        response.setHeader("Expires", httpDateFormat.format(cal.getTime()));

    } else {//  ww w.  ja v a  2  s.c  o  m

        if (!dontCache) {
            response.setHeader("Cache-Control", "no-cache, must-revalidate, proxy-revalidate");
        } else {
            response.setHeader("Cache-Control",
                    "private, no-cache, no-store, max-age=0, s-maxage=0, must-revalidate, proxy-revalidate");
        }

    }

    if (lastModified != null) {

        final Date roundedLastModified = DateUtils.round(lastModified, Calendar.SECOND);
        response.setHeader("Last-Modified", httpDateFormat.format(roundedLastModified));

        final String ifModifiedSince = request.getHeader("If-Modified-Since");

        if (StringUtils.isNotBlank(ifModifiedSince)) {

            try {

                Date ifModSince = httpDateFormat.parse(ifModifiedSince);

                // Note that ifModSince has not ms resolution, so the last digits are always 000
                // That requires the lastModified to be rounded to seconds
                if ((ifModSince != null)
                        && (roundedLastModified.equals(ifModSince) || roundedLastModified.before(ifModSince))) {

                    notModified = true;

                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("Vary", "Accept-Encoding");

                }

            } catch (ParseException ex) {
                logger.log(Level.WARNING, "Could not parse If-Modified-Since header", ex);
            }

        }

    }

    return notModified;
}

From source file:pl.bcichecki.rms.client.android.dialogs.DeviceDetailsDialog.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    if (device == null) {
        throw new IllegalStateException("Device has not been set!");
    }//from w w  w. j  a va  2 s .  c  o  m

    context = getActivity();

    eventsRestClient = new EventsRestClient(getActivity(), UserProfileHolder.getUsername(),
            UserProfileHolder.getPassword(), SharedPreferencesWrapper.getServerRealm(),
            SharedPreferencesWrapper.getServerAddress(), SharedPreferencesWrapper.getServerPort(),
            SharedPreferencesWrapper.getWebserviceContextPath());

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
    dialogBuilder.setTitle(getString(R.string.dialog_device_details_title, device.getName()));
    dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialog_device_details, null));
    dialogBuilder.setNeutralButton(R.string.dialog_device_details_btn_show_reservations,
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    final Date now = new Date();
                    final Date from = DateUtils.round(DateUtils.addDays(now, DAYS_BACK - 1),
                            Calendar.DAY_OF_MONTH);
                    final Date till = DateUtils.round(DateUtils.addDays(now, DAYS_AHEAD + 1),
                            Calendar.DAY_OF_MONTH);

                    final FragmentManager fragmentManager = getFragmentManager();

                    Log.d(getTag(), "Retrieving device's events for " + device);

                    eventsRestClient.getDevicesEvents(device, from, till,
                            new GsonHttpResponseHandler<List<Event>>(new TypeToken<List<Event>>() {
                            }.getType(), true) {

                                @Override
                                public void onFailure(Throwable error, String content) {
                                    Log.d(getTag(),
                                            "Retrieving device's events from " + from.toString() + " till "
                                                    + till.toString() + " failed. [error=" + error
                                                    + ", content=" + content + "]");
                                    if (error instanceof HttpResponseException) {
                                        if (((HttpResponseException) error)
                                                .getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                                            AppUtils.showCenteredToast(context,
                                                    R.string.general_unathorized_error_message_title,
                                                    Toast.LENGTH_LONG);
                                        } else {
                                            AppUtils.showCenteredToast(context,
                                                    R.string.general_unknown_error_message_title,
                                                    Toast.LENGTH_LONG);
                                        }
                                    } else {
                                        AppUtils.showCenteredToast(context,
                                                R.string.general_unknown_error_message_title,
                                                Toast.LENGTH_LONG);
                                    }
                                }

                                @Override
                                public void onFinish() {
                                    Log.d(getTag(), "Retrieving device's events finished.");
                                }

                                @Override
                                public void onStart() {
                                    Log.d(getTag(), "Retrieving device's events from " + from.toString()
                                            + " till " + till.toString() + " started.");
                                }

                                @Override
                                public void onSuccess(int statusCode, List<Event> events) {
                                    Log.d(getTag(),
                                            "Retrieving device's events from " + from.toString() + " till "
                                                    + till.toString() + " successful. Retrieved "
                                                    + events.size() + " objects.");
                                    DeviceReservationsDialog deviceReservationsDialog = new DeviceReservationsDialog();
                                    deviceReservationsDialog.setDevice(device);
                                    deviceReservationsDialog.setEvents(events);
                                    deviceReservationsDialog.show(fragmentManager, getTag());
                                }

                            });
                }
            });
    dialogBuilder.setPositiveButton(R.string.general_close, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // Nothing to do...
        }
    });

    AlertDialog dialog = dialogBuilder.create();
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {
            TextView nameTextView = (TextView) ((AlertDialog) dialog)
                    .findViewById(R.id.dialog_device_details_name_text);
            nameTextView.setText(device.getName());

            TextView descriptionTextView = (TextView) ((AlertDialog) dialog)
                    .findViewById(R.id.dialog_device_details_description_text);
            descriptionTextView.setText(device.getName());
        }
    });

    return dialog;
}

From source file:pl.bcichecki.rms.client.android.fragments.EventsListFragment.java

private void downloadArchivedData() {
    if (!showArchivedEvents) {
        return;// w  w w .  j a  v a 2  s  . co m
    }

    Log.d(TAG, "Downloading events list...");

    if (!AppUtils.checkInternetConnection(getActivity())) {
        Log.d(TAG, "There is NO network connected!");
        return;
    }

    final Date now = new Date();
    final Date from = DateUtils.round(DateUtils.addDays(now, DAYS_BACK - 1), Calendar.DAY_OF_MONTH);
    final Date till = DateUtils.round(DateUtils.addDays(now, DAYS_AHEAD + 1), Calendar.DAY_OF_MONTH);

    eventsRestClient.getAllArchivedEvents(from, till,
            new GsonHttpResponseHandler<List<Event>>(new TypeToken<List<Event>>() {
            }.getType(), true) {

                @Override
                public void onFailure(Throwable error, String content) {
                    Log.d(TAG, "Retrieving archived events from " + from.toString() + " till " + till.toString()
                            + " failed. [error=" + error + ", content=" + content + "]");
                    if (error instanceof HttpResponseException) {
                        if (((HttpResponseException) error).getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                            AppUtils.showCenteredToast(getActivity(),
                                    R.string.general_unathorized_error_message_title, Toast.LENGTH_LONG);
                        } else {
                            AppUtils.showCenteredToast(getActivity(),
                                    R.string.general_unknown_error_message_title, Toast.LENGTH_LONG);
                        }
                    } else {
                        AppUtils.showCenteredToast(getActivity(), R.string.general_unknown_error_message_title,
                                Toast.LENGTH_LONG);
                    }
                }

                @Override
                public void onFinish() {
                    eventsListAdapter.refresh();
                    hideLoadingMessage();
                    Log.d(TAG, "Retrieving archived events finished.");
                }

                @Override
                public void onStart() {
                    Log.d(TAG, "Retrieving archived events from " + from.toString() + " till " + till.toString()
                            + " started.");
                    showLoadingMessage();
                }

                @Override
                public void onSuccess(int statusCode, List<Event> object) {
                    Log.d(TAG, "Retrieving archived events from " + from.toString() + " till " + till.toString()
                            + " successful. Retrieved " + object.size() + " objects.");
                    events.addAll(object);
                }
            });
}

From source file:pl.bcichecki.rms.client.android.fragments.EventsListFragment.java

private void downloadData() {
    Log.d(TAG, "Downloading events list...");

    if (!AppUtils.checkInternetConnection(getActivity())) {
        Log.d(TAG, "There is NO network connected!");
        return;/*from w w w  . j a  v a  2  s  . c  o  m*/
    }

    final Date now = new Date();
    final Date from = DateUtils.round(DateUtils.addDays(now, DAYS_BACK - 1), Calendar.DAY_OF_MONTH);
    final Date till = DateUtils.round(DateUtils.addDays(now, DAYS_AHEAD + 1), Calendar.DAY_OF_MONTH);

    eventsRestClient.getAllEvents(from, till,
            new GsonHttpResponseHandler<List<Event>>(new TypeToken<List<Event>>() {
            }.getType(), true) {

                @Override
                public void onFailure(Throwable error, String content) {
                    Log.d(TAG, "Retrieving events from " + from.toString() + " till " + till.toString()
                            + " failed. [error=" + error + ", content=" + content + "]");
                    if (error instanceof HttpResponseException) {
                        if (((HttpResponseException) error).getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                            AppUtils.showCenteredToast(getActivity(),
                                    R.string.general_unathorized_error_message_title, Toast.LENGTH_LONG);
                        } else {
                            AppUtils.showCenteredToast(getActivity(),
                                    R.string.general_unknown_error_message_title, Toast.LENGTH_LONG);
                        }
                    } else {
                        AppUtils.showCenteredToast(getActivity(), R.string.general_unknown_error_message_title,
                                Toast.LENGTH_LONG);
                    }
                }

                @Override
                public void onFinish() {
                    eventsListAdapter.refresh();
                    hideLoadingMessage();
                    Log.d(TAG, "Retrieving events finished.");
                }

                @Override
                public void onStart() {
                    Log.d(TAG, "Retrieving events from " + from.toString() + " till " + till.toString()
                            + " started.");
                    showLoadingMessage();
                    events.clear();
                }

                @Override
                public void onSuccess(int statusCode, List<Event> object) {
                    Log.d(TAG, "Retrieving events from " + from.toString() + " till " + till.toString()
                            + " successful. Retrieved " + object.size() + " objects.");
                    events.addAll(object);
                }
            });
}

From source file:ubic.gemma.core.analysis.preprocess.svd.SVDServiceHelperImpl.java

/**
 * Do the factor comparisons for one component.
 *
 * @param bioMaterialFactorMap Map of factors to biomaterials to the value we're going to use. Even for
 *                             non-continuous factors the value is a double.
 *//*from  w w w . j  a v a 2  s .c o  m*/
private void analyzeComponent(SVDValueObject svo, int componentNumber, DoubleMatrix<Long, Integer> vMatrix,
        Map<Long, Date> bioMaterialDates, Map<ExperimentalFactor, Map<Long, Double>> bioMaterialFactorMap,
        Long[] svdBioMaterials) {
    DoubleArrayList eigenGene = new DoubleArrayList(vMatrix.getColumn(componentNumber));
    // since we use rank correlation/anova, we just use the casted ids (two-groups) or dates as the covariate

    int numWithDates = 0;
    for (Long id : bioMaterialDates.keySet()) {
        if (bioMaterialDates.get(id) != null) {
            numWithDates++;
        }
    }

    if (numWithDates > 2) {
        /*
         * Get the dates in order, - no rounding.
         */
        boolean initializingDates = svo.getDates().isEmpty();
        double[] dates = new double[svdBioMaterials.length];

        /*
         * If dates are all the same, skip.
         */
        Set<Date> uniqueDate = new HashSet<>();

        for (int j = 0; j < svdBioMaterials.length; j++) {

            Date date = bioMaterialDates.get(svdBioMaterials[j]);
            if (date == null) {
                SVDServiceHelperImpl.log
                        .warn("Incomplete date information, missing for biomaterial " + svdBioMaterials[j]);
                dates[j] = Double.NaN;
            } else {
                Date roundDate = DateUtils.round(date, Calendar.MINUTE);
                uniqueDate.add(roundDate);
                dates[j] = roundDate.getTime(); // round to minute; make int, cast to
                // double
            }

            if (initializingDates) {
                svo.getDates().add(date);
            }
        }

        if (uniqueDate.size() == 1) {
            SVDServiceHelperImpl.log.warn("All scan dates the same, skipping data analysis");
            svo.getDates().clear();
        }

        if (eigenGene.size() != dates.length) {
            SVDServiceHelperImpl.log
                    .warn("Could not compute correlation, dates and eigenGene had different lengths.");
            return;
        }

        double dateCorrelation = Distance.spearmanRankCorrelation(eigenGene, new DoubleArrayList(dates));

        svo.setPCDateCorrelation(componentNumber, dateCorrelation);
        svo.setPCDateCorrelationPval(componentNumber,
                CorrelationStats.spearmanPvalue(dateCorrelation, eigenGene.size()));
    }

    /*
     * Compare each factor (including batch information that is somewhat redundant with the dates) to the
     * eigen-genes. Using rank statistics.
     */
    for (ExperimentalFactor ef : bioMaterialFactorMap.keySet()) {
        Map<Long, Double> bmToFv = bioMaterialFactorMap.get(ef);

        double[] fvs = new double[svdBioMaterials.length];
        assert fvs.length > 0;

        int numNotMissing = 0;

        boolean initializing = false;
        if (!svo.getFactors().containsKey(ef.getId())) {
            svo.getFactors().put(ef.getId(), new ArrayList<Double>());
            initializing = true;
        }

        for (int j = 0; j < svdBioMaterials.length; j++) {
            fvs[j] = bmToFv.get(svdBioMaterials[j]);
            if (!Double.isNaN(fvs[j])) {
                numNotMissing++;
            }
            // note that this is a double. In the case of categorical factors, it's the Double-fied ID of the factor
            // value.
            if (initializing) {
                if (SVDServiceHelperImpl.log.isDebugEnabled())
                    SVDServiceHelperImpl.log
                            .debug("EF:" + ef.getId() + " fv=" + bmToFv.get(svdBioMaterials[j]));
                svo.getFactors().get(ef.getId()).add(bmToFv.get(svdBioMaterials[j]));
            }
        }

        if (fvs.length != eigenGene.size()) {
            SVDServiceHelperImpl.log.debug(fvs.length + " factor values (biomaterials) but " + eigenGene.size()
                    + " values in the eigenGene");
            continue;
        }

        if (numNotMissing < SVDServiceHelperImpl.MINIMUM_POINTS_TO_COMPARE_TO_EIGEN_GENE) {
            SVDServiceHelperImpl.log.debug("Insufficient values to compare " + ef + " to eigenGenes");
            continue;
        }

        if (ExperimentalDesignUtils.isContinuous(ef)) {
            double factorCorrelation = Distance.spearmanRankCorrelation(eigenGene, new DoubleArrayList(fvs));
            svo.setPCFactorCorrelation(componentNumber, ef, factorCorrelation);
            svo.setPCFactorCorrelationPval(componentNumber, ef,
                    CorrelationStats.spearmanPvalue(factorCorrelation, eigenGene.size()));
        } else {

            Collection<Integer> groups = new HashSet<>();
            IntArrayList groupings = new IntArrayList(fvs.length);
            int k = 0;
            DoubleArrayList eigenGeneWithoutMissing = new DoubleArrayList();
            for (double d : fvs) {
                if (Double.isNaN(d)) {
                    k++;
                    continue;
                }
                groupings.add((int) d);
                groups.add((int) d);
                eigenGeneWithoutMissing.add(eigenGene.get(k));
                k++;
            }

            if (groups.size() < 2) {
                SVDServiceHelperImpl.log
                        .debug("Factor had less than two groups: " + ef + ", SVD comparison can't be done.");
                continue;
            }

            if (eigenGeneWithoutMissing.size() < SVDServiceHelperImpl.MINIMUM_POINTS_TO_COMPARE_TO_EIGEN_GENE) {
                SVDServiceHelperImpl.log
                        .debug("Too few non-missing values for factor to compare to eigenGenes: " + ef);
                continue;
            }

            if (groups.size() == 2) {
                // use the one that still has missing values.
                double factorCorrelation = Distance.spearmanRankCorrelation(eigenGene,
                        new DoubleArrayList(fvs));
                svo.setPCFactorCorrelation(componentNumber, ef, factorCorrelation);
                svo.setPCFactorCorrelationPval(componentNumber, ef,
                        CorrelationStats.spearmanPvalue(factorCorrelation, eigenGeneWithoutMissing.size()));
            } else {
                // one-way ANOVA on ranks.
                double kwPVal = KruskalWallis.test(eigenGeneWithoutMissing, groupings);

                svo.setPCFactorCorrelationPval(componentNumber, ef, kwPVal);

                double factorCorrelation = Distance.spearmanRankCorrelation(eigenGene,
                        new DoubleArrayList(fvs));
                double corrPvalue = CorrelationStats.spearmanPvalue(factorCorrelation,
                        eigenGeneWithoutMissing.size());
                assert Math.abs(factorCorrelation) < 1.0 + 1e-2; // sanity.
                /*
                 * Avoid storing a pvalue, as it's hard to compare. If the regular linear correlation is strong,
                 * then we should just use that -- basically, it means the order we have the groups happens to be a
                 * good one. Of course we could just store pvalues, but that's not easy to use either.
                 */
                if (corrPvalue <= kwPVal) {
                    svo.setPCFactorCorrelation(componentNumber, ef, factorCorrelation);
                } else {
                    // hack. A bit like turning pvalues into prob it
                    double approxCorr = CorrelationStats.correlationForPvalue(kwPVal,
                            eigenGeneWithoutMissing.size());
                    svo.setPCFactorCorrelation(componentNumber, ef, approxCorr);

                }
            }

        }
    }
}