Example usage for java.util GregorianCalendar set

List of usage examples for java.util GregorianCalendar set

Introduction

In this page you can find the example usage for java.util GregorianCalendar set.

Prototype

public void set(int field, int value) 

Source Link

Document

Sets the given calendar field to the given value.

Usage

From source file:ca.mudar.parkcatcher.ui.activities.MainActivity.java

private void updateParkingTimeFromUri(Uri uri) {
    Log.v(TAG, "updateParkingTimeFromUri");
    List<String> pathSegments = uri.getPathSegments();

    // http://www.capteurdestationnement.com/map/search/2/15.5/12
    // http://www.capteurdestationnement.com/map/search/2/15.5/12/h2w2e7

    if ((pathSegments.size() >= 5) && (pathSegments.get(0).equals(Const.INTENT_EXTRA_URL_PATH_MAP))
            && (pathSegments.get(1).equals(Const.INTENT_EXTRA_URL_PATH_SEARCH))) {

        try {//from ww w . j a va 2  s  .  c o  m
            final int day = Integer.valueOf(pathSegments.get(2));
            final double time = Double.valueOf(pathSegments.get(3));
            final int duration = Integer.valueOf(pathSegments.get(4));

            final int hourOfDay = (int) time;
            final int minute = (int) ((time - hourOfDay) * 60);

            GregorianCalendar calendar = new GregorianCalendar();

            calendar.set(Calendar.DAY_OF_WEEK, day == 7 ? Calendar.SUNDAY : day + 1);
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);

            parkingApp.setParkingCalendar(calendar);
            parkingApp.setParkingDuration(duration);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.jhuapl.openessence.web.util.Filters.java

private Date muckDate(Date date, int prepull, String resolution, int calWeekStartDay) {
    GregorianCalendar x = new GregorianCalendar();
    x.setTime(date);//from   w w w .  j  a  va 2  s. c o  m
    if (resolution != null && resolution.equals("weekly")) {
        x.add(Calendar.DATE, (-7 * prepull));
        // make sure week starts on week start day defined
        // in message.properties or datasource groovy file
        while (x.get(Calendar.DAY_OF_WEEK) != calWeekStartDay) {
            x.add(Calendar.DATE, -1);
        }
    } else if (resolution != null && resolution.equals("monthly")) {
        x.set(Calendar.DAY_OF_MONTH, 1);
    } else if (resolution != null && resolution.equals("daily")) {
        x.add(Calendar.DATE, -prepull);
    }
    return x.getTime();
}

From source file:org.modelibra.type.EasyCalendar.java

/**
 * Gets the last day in year, month.//from w w w .jav  a2  s .c  o  m
 * 
 * @param year
 *            year
 * @param month
 *            month
 * @return the last day in year, month
 */
public int getLastDay(int year, int month) {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month - 1); // months start with 0
    int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    return day;
}

From source file:eionet.util.Util.java

/**
 * A method for calculating time difference in MILLISECONDS, between a date-time specified in input parameters and the current
 * date-time. <BR>/*from w w w.ja v a 2s  .c  om*/
 * This should be useful for calculating sleep time for code that has a certain schedule for execution.
 *
 * @param hour
 *            An integer from 0 to 23. If less than 0 or more than 23, then the closest next hour to current hour is taken.
 * @param date
 *            An integer from 1 to 31. If less than 1 or more than 31, then the closest next date to current date is taken.
 * @param month
 *            An integer from Calendar.JANUARY to Calendar.DECEMBER. If out of those bounds, the closest next month to current
 *            month is taken.
 * @param wday
 *            An integer from 1 to 7. If out of those bounds, the closest next weekday to weekday month is taken.
 * @param zone
 *            A String specifying the time-zone in which the calculations should be done. Please see Java documentation an
 *            allowable time-zones and formats.
 * @return Time difference in milliseconds.
 */
public static long timeDiff(int hour, int date, int month, int wday, String zone) {

    GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone(zone));
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    cal.setFirstDayOfWeek(Calendar.MONDAY);

    /*
     * here we force the hour to be one of the defualts if (hour < 0) hour = 0; if (hour > 23) hour = 23;
     */
    int cur_hour = cal.get(Calendar.HOUR);

    if (cal.get(Calendar.AM_PM) == Calendar.PM) {
        cur_hour = 12 + cur_hour;
    }

    // here we assume that every full hour is accepted
    /*
     * if (hour < 0 || hour > 23) { hour = cur_hour>=23 ? 0 : cur_hour + 1; }
     */

    if (wday >= 1 && wday <= 7) {

        int cur_wday = cal.get(Calendar.DAY_OF_WEEK);
        if (hour < 0 || hour > 23) {
            if (cur_wday != wday) {
                hour = 0;
            } else {
                hour = cur_hour >= 23 ? 0 : cur_hour + 1;
            }
        }

        int amount = wday - cur_wday;
        if (amount < 0) {
            amount = 7 + amount;
        }
        if (amount == 0 && cur_hour >= hour) {
            amount = 7;
        }
        cal.add(Calendar.DAY_OF_WEEK, amount);
    } else if (month >= Calendar.JANUARY && month <= Calendar.DECEMBER) { // do something about when every date is accepted
        if (date < 1) {
            date = 1;
        }
        if (date > 31) {
            date = 31;
        }
        int cur_month = cal.get(Calendar.MONTH);
        int amount = month - cur_month;
        if (amount < 0) {
            amount = 12 + amount;
        }
        if (amount == 0) {
            if (cal.get(Calendar.DATE) > date) {
                amount = 12;
            } else if (cal.get(Calendar.DATE) == date) {
                if (cur_hour >= hour) {
                    amount = 12;
                }
            }
        }
        // cal.set(Calendar.DATE, date);
        cal.add(Calendar.MONTH, amount);
        if (date > cal.getActualMaximum(Calendar.DATE)) {
            date = cal.getActualMaximum(Calendar.DATE);
        }
        cal.set(Calendar.DATE, date);
    } else if (date >= 1 && date <= 31) {
        int cur_date = cal.get(Calendar.DATE);
        if (cur_date > date) {
            cal.add(Calendar.MONTH, 1);
        } else if (cur_date == date) {
            if (cur_hour >= hour) {
                cal.add(Calendar.MONTH, 1);
            }
        }
        cal.set(Calendar.DATE, date);
    } else {
        if (hour < 0 || hour > 23) {
            hour = cur_hour >= 23 ? 0 : cur_hour + 1;
        }
        if (cur_hour >= hour) {
            cal.add(Calendar.DATE, 1);
        }
    }

    if (hour >= 12) {
        cal.set(Calendar.HOUR, hour - 12);
        cal.set(Calendar.AM_PM, Calendar.PM);
    } else {
        cal.set(Calendar.HOUR, hour);
        cal.set(Calendar.AM_PM, Calendar.AM);
    }

    Date nextDate = cal.getTime();
    Date currDate = new Date();

    long nextTime = cal.getTime().getTime();
    long currTime = (new Date()).getTime();

    return nextTime - currTime;
}

From source file:org.modelibra.type.EasyCalendar.java

/**
 * Gets a date from year, month and day numbers. Hours, minutes, seconds and
 * milliseconds are set to 0.//from w w  w  .j  a v a 2  s .c  om
 * 
 * @param year
 *            year
 * @param month
 *            month
 * @param day
 *            day
 * @return date
 */
public Date getDate(int year, int month, int day) {
    // short lived calendar, just for this conversion
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month - 1); // months start with 0
    calendar.set(Calendar.DAY_OF_MONTH, day);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    Date date = calendar.getTime();
    return date;
}

From source file:org.modelibra.type.EasyCalendar.java

/**
 * Gets a date time from year, month, day, hour, minute, second numbers.
 * Milliseconds are set to 0./*w ww  .  j av  a  2s  . c o m*/
 * 
 * @param year
 *            year
 * @param month
 *            month
 * @param day
 *            day
 * @param hour
 *            hour
 * @param minute
 *            minute
 * @param second
 *            second
 * @return date time
 */
public Date getDateTime(int year, int month, int day, int hour, int minute, int second) {
    // short lived calendar, just for this conversion
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month - 1); // months start with 0
    calendar.set(Calendar.DAY_OF_MONTH, day);
    calendar.set(Calendar.HOUR, hour);
    calendar.set(Calendar.MINUTE, minute);
    calendar.set(Calendar.SECOND, second);
    calendar.set(Calendar.MILLISECOND, 0);
    Date date = calendar.getTime();
    return date;
}

From source file:org.hyperic.hq.ui.action.resource.common.monitor.alerts.ListAlertAction.java

/**
 * Create a list of AlertBean objects based on the AlertValue objects for
 * this resource.//  ww  w  . j av a  2 s .  c om
 */
public ActionForward execute(ComponentContext context, ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    int sessionId = RequestUtils.getSessionId(request).intValue();
    AppdefEntityID appEntId = RequestUtils.getEntityId(request);

    GregorianCalendar cal = new GregorianCalendar();

    try {
        Integer year = RequestUtils.getIntParameter(request, "year");
        Integer month = RequestUtils.getIntParameter(request, "month");
        Integer day = RequestUtils.getIntParameter(request, "day");

        cal.set(Calendar.YEAR, year.intValue());
        cal.set(Calendar.MONTH, month.intValue());
        cal.set(Calendar.DAY_OF_MONTH, day.intValue());
    } catch (ParameterNotFoundException e) {
        // Ignore
    }

    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);

    PageControl pc = RequestUtils.getPageControl(request);

    try {
        RequestUtils.getIntParameter(request, Constants.SORTCOL_PARAM);
    } catch (ParameterNotFoundException e) {
        // By default we sort by descending ctime
        pc.setSortorder(PageControl.SORT_DESC);
    }

    PageList<Alert> alerts;

    try {
        final DateTime begin = new DateTime(cal);
        final DateTime end = addAlmostOneDay(begin);
        alerts = eventsBoss.findAlerts(sessionId, appEntId, begin.getMillis(), end.getMillis(), pc);
    } catch (PermissionException e) {
        // user is not allowed to see/manage alerts.
        // return empty list for now
        alerts = new PageList<Alert>();
    }

    PageList<AlertBean> uiBeans = new PageList<AlertBean>();

    AuthzSubject subject = authzBoss.getCurrentSubject(sessionId);
    boolean canTakeAction = false;
    try {
        // ...check that the user can fix/acknowledge...
        alertPermissionManager.canFixAcknowledgeAlerts(subject, appEntId);
        canTakeAction = true;
    } catch (PermissionException e) {
        // ...the user can't fix/acknowledge...
    }

    for (Alert alert : alerts) {

        AlertDefinition alertDefinition = alert.getAlertDefinition();
        AlertBean bean = new AlertBean(alert.getId(), alert.getCtime(), alertDefinition.getId(),
                alertDefinition.getName(), alertDefinition.getPriority(), appEntId.getId(),
                new Integer(appEntId.getType()), alert.isFixed(), alert.isAckable(), canTakeAction);
        Escalation escalation = alertDefinition.getEscalation();

        if (escalation != null && escalation.isPauseAllowed()) {
            bean.setMaxPauseTime(escalation.getMaxPauseTime());
        }

        // Determine whether or not this alert definition is viewable
        bean.setViewable(!alertDefinition.isDeleted() && alertDefinition.getResource() != null
                && !alertDefinition.getResource().isInAsyncDeleteState());

        Collection<AlertConditionLog> conditionLogs = alert.getConditionLog();

        if (conditionLogs.size() > 1) {
            setupMultiCondition(bean, request);
        } else if (conditionLogs.size() == 1) {
            AlertConditionLog conditionLog = (AlertConditionLog) conditionLogs.iterator().next();
            AlertConditionValue condition = conditionLog.getCondition().getAlertConditionValue();

            setupCondition(bean, condition, conditionLog.getValue(), request,

                    sessionId);
        } else {
            // fall back to alert definition conditions: PR 6992
            Collection<AlertCondition> conditions = alertDefinition.getConditions();

            if (conditions.size() > 1) {
                setupMultiCondition(bean, request);
            } else if (conditions.size() == 1) {
                AlertCondition condition = conditions.iterator().next();

                setupCondition(bean, condition.getAlertConditionValue(), null, request,

                        sessionId);
            } else {
                // *serious* trouble
                log.error("No condition logs for alert: " + alert.getId());

                bean.setMultiCondition(true);
                bean.setConditionName(Constants.UNKNOWN);
                bean.setValue(Constants.UNKNOWN);
            }
        }

        uiBeans.add(bean);
    }

    context.putAttribute(Constants.RESOURCE_ATTR, RequestUtils.getResource(request));
    context.putAttribute(Constants.RESOURCE_OWNER_ATTR, request.getAttribute(Constants.RESOURCE_OWNER_ATTR));
    context.putAttribute(Constants.RESOURCE_MODIFIER_ATTR,
            request.getAttribute(Constants.RESOURCE_MODIFIER_ATTR));
    request.setAttribute(Constants.ALERTS_ATTR, uiBeans);
    request.setAttribute(Constants.LIST_SIZE_ATTR, new Integer(alerts.getTotalSize()));

    return null;
}

From source file:org.oscarehr.PMmodule.web.GenericIntakeSearchAction.java

private void createRemoteList(HttpServletRequest request, GenericIntakeSearchFormBean intakeSearchBean) {
    try {//from w w  w .  j  a v a2  s  . co  m
        DemographicWs demographicWs = CaisiIntegratorManager.getDemographicWs();

        MatchingDemographicParameters parameters = new MatchingDemographicParameters();
        parameters.setMaxEntriesToReturn(10);
        parameters.setMinScore(7);

        String temp = StringUtils.trimToNull(intakeSearchBean.getFirstName());
        parameters.setFirstName(temp);

        temp = StringUtils.trimToNull(intakeSearchBean.getLastName());
        parameters.setLastName(temp);

        temp = StringUtils.trimToNull(intakeSearchBean.getHealthCardNumber());
        parameters.setHin(temp);

        GregorianCalendar cal = new GregorianCalendar();
        {
            MiscUtils.setToBeginningOfDay(cal);

            temp = StringUtils.trimToNull(intakeSearchBean.getYearOfBirth());
            if (temp != null)
                cal.set(Calendar.YEAR, Integer.parseInt(temp));

            temp = StringUtils.trimToNull(intakeSearchBean.getMonthOfBirth());
            if (temp != null)
                cal.set(Calendar.MONTH, Integer.parseInt(temp));

            temp = StringUtils.trimToNull(intakeSearchBean.getDayOfBirth());
            if (temp != null)
                cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(temp));

            parameters.setBirthDate(cal);
        }

        List<MatchingDemographicTransferScore> integratedMatches = demographicWs
                .getMatchingDemographics(parameters);
        request.setAttribute("remoteMatches", integratedMatches);

        List<CachedFacility> allFacilities = CaisiIntegratorManager.getRemoteFacilities();
        HashMap<Integer, String> facilitiesNameMap = new HashMap<Integer, String>();
        for (CachedFacility cachedFacility : allFacilities)
            facilitiesNameMap.put(cachedFacility.getIntegratorFacilityId(), cachedFacility.getName());

        request.setAttribute("facilitiesNameMap", facilitiesNameMap);
    } catch (WebServiceException e) {
        LOG.warn("Error connecting to integrator. " + e.getMessage());
        LOG.debug("Error connecting to integrator.", e);
    } catch (Exception e) {
        LOG.error("Unexpected error.", e);
    }
}

From source file:ca.mudar.parkcatcher.ui.fragments.DetailsFragment.java

private int getIdFromUri(Uri uri) {
    int postId = -1;

    List<String> pathSegments = uri.getPathSegments();

    if ((pathSegments.size() == 5) && (pathSegments.get(0).equals(Const.INTENT_EXTRA_URL_PATH_POST_ID))) {

        try {/*  w w w.j av a2  s.co m*/
            postId = Integer.parseInt(pathSegments.get(1));
            final int day = Integer.valueOf(pathSegments.get(2));
            final double time = Double.valueOf(pathSegments.get(3));
            final int duration = Integer.valueOf(pathSegments.get(4));

            final int hourOfDay = (int) time;
            final int minute = (int) ((time - hourOfDay) * 60);

            GregorianCalendar calendar = new GregorianCalendar();

            calendar.set(Calendar.DAY_OF_WEEK, day == 7 ? Calendar.SUNDAY : day + 1);
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);

            parkingApp.setParkingCalendar(calendar);
            // parkingApp.setParkingTime(hourOfDay, minute);
            parkingApp.setParkingDuration(duration);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    return postId;
}

From source file:ca.uhn.hl7v2.model.primitive.CommonTSTest.java

@Test
public void testToHl7TMFormat() throws DataTypeException {
    GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("America/Toronto"));
    cal.clear();/*w  ww  . j av a2 s.  c o m*/
    cal.setLenient(false);
    cal.set(Calendar.HOUR_OF_DAY, 20);
    cal.set(Calendar.MINUTE, 6);
    cal.set(Calendar.SECOND, 24);
    cal.set(Calendar.MILLISECOND, 528);
    String convertedDate = CommonTM.toHl7TMFormat(cal);
    assertEquals("Should get a HL7 formatted date back", "200624.528-0500", convertedDate);
}