Example usage for java.util Calendar clone

List of usage examples for java.util Calendar clone

Introduction

In this page you can find the example usage for java.util Calendar clone.

Prototype

@Override
public Object clone() 

Source Link

Document

Creates and returns a copy of this object.

Usage

From source file:nl.strohalm.cyclos.utils.DateHelper.java

/**
 * sets the time of the day of the first argument, so that it is equal to the time of the day of the second argument.
 * @param toEqualize a Calendar, whose time will be equalized to the source's time of the day
 * @param source the time of the day of this Calendar is taken.
 * @return a new Calendar object, with the date equal to toEqualize, but the time of the date is equal to that of the source Calendar.
 */// w w w .  ja  va2 s  .c o m
public static Calendar equalizeTime(final Calendar toEqualize, final Calendar source) {
    if (source == null) {
        return null;
    }
    final int hourOfDay = source.get(Calendar.HOUR_OF_DAY);
    final int minute = source.get(Calendar.MINUTE);
    final int second = source.get(Calendar.SECOND);
    final int milliSecond = source.get(Calendar.MILLISECOND);
    final Calendar result = (Calendar) toEqualize.clone();
    result.set(Calendar.HOUR_OF_DAY, hourOfDay);
    result.set(Calendar.MINUTE, minute);
    result.set(Calendar.SECOND, second);
    result.set(Calendar.MILLISECOND, milliSecond);
    return result;
}

From source file:net.seratch.taskun.util.CalendarUtil.java

 public static Calendar dateTrunc(Calendar calendar) {
   if (calendar == null) {
      return null;
   }/*from   ww w  .j  a  va 2 s  .com*/
   Calendar date = (Calendar) calendar.clone();
   date.set(Calendar.HOUR_OF_DAY, 0);
   date.set(Calendar.MINUTE, 0);
   date.set(Calendar.SECOND, 0);
   date.set(Calendar.MILLISECOND, 0);
   return date;
}

From source file:org.jasig.schedassist.model.AvailableBlockBuilder.java

/**
 * //from   ww  w. j av  a2 s  .  c om
 * @param startTimePhrase
 * @param endTimePhrase
 * @param daysOfWeekPhrase
 * @param startDate
 * @param endDate
 * @param visitorLimit
 * @param meetingLocation
 * @return
 * @throws InputFormatException
 */
public static SortedSet<AvailableBlock> createBlocks(final String startTimePhrase, final String endTimePhrase,
        final String daysOfWeekPhrase, final Date startDate, final Date endDate, final int visitorLimit,
        final String meetingLocation) throws InputFormatException {
    SortedSet<AvailableBlock> blocks = new TreeSet<AvailableBlock>();
    // set time of startDate to 00:00:00
    Date realStartDate = DateUtils.truncate(startDate, Calendar.DATE);
    // set time of endDate to 23:59:59
    Date dayAfterEndDate = DateUtils.truncate(DateUtils.addDays(endDate, 1), Calendar.DATE);
    Date realEndDate = DateUtils.addSeconds(dayAfterEndDate, -1);

    if (LOG.isDebugEnabled()) {
        LOG.debug("createBlocks calculated realStartDate: " + realStartDate + ", realEndDate: " + realEndDate);
    }

    List<Date> matchingDays = matchingDays(daysOfWeekPhrase, realStartDate, realEndDate);
    for (Date matchingDate : matchingDays) {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(matchingDate);
        Calendar endCalendar = (Calendar) startCalendar.clone();

        interpretAndUpdateTime(startTimePhrase, startCalendar);
        interpretAndUpdateTime(endTimePhrase, endCalendar);

        Date blockStartTime = startCalendar.getTime();
        Date blockEndTime = endCalendar.getTime();
        if (!blockEndTime.after(blockStartTime)) {
            throw new InputFormatException("Start time must occur before end time");
        }
        if (CommonDateOperations.equalsOrAfter(blockStartTime, realStartDate)
                && CommonDateOperations.equalsOrBefore(blockEndTime, realEndDate)) {
            AvailableBlock block = new AvailableBlock(blockStartTime, blockEndTime, visitorLimit,
                    meetingLocation);
            blocks.add(block);
        }

    }
    return blocks;
}

From source file:org.apache.usergrid.apm.util.GenerateSimulatedMobileData.java

public static ClientNetworkMetrics getGeneratedMetricBean(Long givenAppId, MobileSession s,
        ClientSessionMetrics csm) {/*ww w .  j a  va  2  s . c  o  m*/
    ClientNetworkMetrics bean = new ClientNetworkMetrics();
    //bean.setAppConfigType(configs[generator.nextInt(4)]);

    int index = generator.nextInt(wsUrls.length);

    bean.setUrl(wsUrls[index]);

    Calendar prevEnd = Calendar.getInstance();
    prevEnd.setTime(s.getEndTime());

    Calendar end = Calendar.getInstance();

    int diff = (int) (end.getTimeInMillis() - prevEnd.getTimeInMillis()) / 1000; //diff in seconds

    Calendar startTime = (Calendar) prevEnd.clone();
    startTime.add(Calendar.SECOND, diff / 2);
    bean.setStartTime(startTime.getTime());

    Calendar endTime = (Calendar) startTime.clone();
    endTime.add(Calendar.SECOND, diff / 3);
    bean.setEndTime(endTime.getTime());
    bean.setTimeStamp(endTime.getTime());

    long latency = getSimulatedLatency(csm.getNetworkSubType(), csm.getTelephonyNetworkOperatorName(),
            bean.getUrl());
    int numError = getFailureRate(csm.getNetworkSubType(), csm.getTelephonyNetworkOperatorName(),
            bean.getUrl());

    Long statusCode;
    if (numError == 0)
        statusCode = 200L;
    else
        statusCode = httpStatusCodes[generator.nextInt(httpStatusCodes.length)];
    bean.setHttpStatusCode(statusCode);
    bean.setLatency(latency);
    bean.setNumSamples(1L);
    bean.setNumErrors(Long.valueOf(numError));
    //set server side latency
    int serverLatencyWeight = generator.nextInt(50) + 10;
    bean.setServerProcessingTime((latency * serverLatencyWeight) / 100);

    return bean;
}

From source file:helper.util.DateHelper.java

/**
 * @return the days between two calendars, including dealing with year boundary
 **///from ww  w.  j  a va2  s  .c o m
public static int calculateIntervalInDays(CalendarRange range) {
    Calendar start = range.getStart();
    Calendar end = range.getEnd();
    int startYear = start.get(Calendar.YEAR);
    int endYear = end.get(Calendar.YEAR);
    if (startYear == endYear) {
        if (start.get(Calendar.DAY_OF_YEAR) == end.get(Calendar.DAY_OF_YEAR)) {
            return 0;
        }
        return end.get(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR);
    } else if (start.getTimeInMillis() < end.getTimeInMillis()) {
        // let the calendar do the thinking, just increment date until we hit our end date
        Calendar startCopy = (Calendar) start.clone();
        int days = 0;
        while (true) {
            startCopy.add(Calendar.DATE, 1);
            days++;
            if (startCopy.get(Calendar.DAY_OF_YEAR) == end.get(Calendar.DAY_OF_YEAR)) {
                return days;
            }
        }
    } else {
        // let the calendar do the thinking, just increment date until we hit our end date
        Calendar startCopy = (Calendar) start.clone();
        int days = 0;
        while (true) {
            startCopy.add(Calendar.DATE, -1);
            days--;
            if (startCopy.get(Calendar.DAY_OF_YEAR) == end.get(Calendar.DAY_OF_YEAR)) {
                return days;
            }
        }
    }
}

From source file:au.com.ish.derbydump.derbydump.main.DumpTest.java

@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> setupTestMatrix() throws Exception {
    List<Object[]> result = new ArrayList<Object[]>();

    //testing numbers (BIGINT, DECIMAL, REAL, SMALLINT, INTEGER, DOUBLE)
    {/*  ww w .ja  v  a  2s .  c o  m*/
        //standard set of numbers
        String[] columns = new String[] { "c1 BIGINT", "c2 DECIMAL(10,2)", "c3 REAL", "c4 SMALLINT",
                "c5 INTEGER", "c6 DOUBLE" };
        Object[] row1 = new Object[] { new BigInteger("12"), new BigDecimal("12.12"), new Float("12.1"),
                Integer.valueOf(12), Integer.valueOf(24), Double.valueOf(12.12) };
        String validOutput1 = "(12,12.12,12.1,12,24,12.12),";
        Object[] row2 = new Object[] { new BigInteger("42"), new BigDecimal("42.12"), new Float("42.14"),
                Integer.valueOf(42), Integer.valueOf(64), Double.valueOf(42.14) };
        String validOutput2 = "(42,42.12,42.14,42,64,42.14),";
        Object[] row3 = new Object[] { new BigInteger("42"), new BigDecimal("42"), new Float("42"),
                Integer.valueOf(42), Integer.valueOf(64), Double.valueOf(42) };
        String validOutput3 = "(42,42.00,42.0,42,64,42.0),";
        Object[] row4 = new Object[] { new BigInteger("42"), new BigDecimal("42.1234"), new Float("42.1434"),
                Integer.valueOf(42), Integer.valueOf(64), Double.valueOf(42.1234) };
        String validOutput4 = "(42,42.12,42.1434,42,64,42.1234),";
        Object[] row5 = new Object[] { BigDecimal.ZERO, BigDecimal.ZERO, new Float("0"), Integer.valueOf(0),
                Integer.valueOf(0), Double.valueOf(0) };
        String validOutput5 = "(0,0.00,0.0,0,0,0.0),";
        //test nulls
        Object[] row6 = new Object[] { null, null, null, null, null, null };
        String validOutput6 = "(NULL,NULL,NULL,NULL,NULL,NULL);";
        Object[] values = new Object[] { row1, row2, row3, row4, row5, row6 };
        String[] validOutput = new String[] { validOutput1, validOutput2, validOutput3, validOutput4,
                validOutput5, validOutput6 };

        result.add(new Object[] { "testNumbers", null, columns, values, validOutput, false, false });
    }

    //testing strings
    {
        String[] columns = new String[] { "c1 VARCHAR(20)", "c2 VARCHAR(20)", "c3 VARCHAR(20)" };
        //test normal characters
        Object[] row1 = new Object[] { "123", "abc", "" };
        String validOutput1 = "('123','abc',''),";
        //test nulls
        Object[] row2 = new Object[] { "%", null, "" };
        String validOutput2 = "('%',NULL,''),";
        //test quotes and tabs
        Object[] row3 = new Object[] { "'test'", "\"test\"", "\t" };
        String validOutput3 = "('\\'test\\'','\"test\"','\\t'),";
        //test new line chars
        Object[] row4 = new Object[] { "\n", "\r", "\n\r" };
        String validOutput4 = "('\\n','\\r','\\n\\r');";

        Object[] values = new Object[] { row1, row2, row3, row4 };
        String[] validOutput = new String[] { validOutput1, validOutput2, validOutput3, validOutput4 };

        result.add(new Object[] { "testStrings", null, columns, values, validOutput, false, false });
    }

    //testing dates
    {
        String[] columns = new String[] { "c1 TIMESTAMP", "c2 TIMESTAMP" };
        // test standard dates
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
        c.set(Calendar.YEAR, 2013);
        c.set(Calendar.MONTH, 5);
        c.set(Calendar.DAY_OF_MONTH, 6);
        c.set(Calendar.HOUR_OF_DAY, 11);
        c.set(Calendar.MINUTE, 10);
        c.set(Calendar.SECOND, 10);
        c.set(Calendar.MILLISECOND, 11);

        Calendar c2 = (Calendar) c.clone();
        c2.add(Calendar.DATE, -5000);

        Object[] row1 = new Object[] { c.getTime(), c2.getTime() };
        String validOutput1 = "('2013-06-06 11:10:10.011','1999-09-28 11:10:10.011'),";
        Object[] row2 = new Object[] { "2012-07-07 08:54:33", "1999-09-09 10:04:10" };
        String validOutput2 = "('2012-07-07 08:54:33.0','1999-09-09 10:04:10.0'),";
        Object[] row3 = new Object[] { null, null };
        String validOutput3 = "(NULL,NULL);";
        Object[] values = new Object[] { row1, row2, row3 };
        String[] validOutput = new String[] { validOutput1, validOutput2, validOutput3 };

        result.add(new Object[] { "testDates", null, columns, values, validOutput, false, false });
    }

    //testing CLOB
    {
        String[] columns = new String[] { "c1 CLOB" };
        Object[] row1 = new Object[] { "<clob value here>" };
        String validOutput1 = "('<clob value here>'),";
        Object[] row2 = new Object[] { null };
        String validOutput2 = "(NULL);";
        Object[] values = new Object[] { row1, row2 };
        String[] validOutput = new String[] { validOutput1, validOutput2 };

        result.add(new Object[] { "testClob", null, columns, values, validOutput, false, false });
    }

    //testing BLOB
    {
        String[] columns = new String[] { "c1 BLOB" };
        Object[] row1 = new Object[] { getTestImage() };
        Blob serialBlob = new SerialBlob(IOUtils.toByteArray(getTestImage()));
        String validOutput1 = "(" + Column.processBinaryData(serialBlob) + "),";
        Object[] row2 = new Object[] { null };
        String validOutput2 = "(NULL);";
        Object[] values = new Object[] { row1, row2 };
        String[] validOutput = new String[] { validOutput1, validOutput2 };

        result.add(new Object[] { "testBlob", null, columns, values, validOutput, false, false });
    }

    //testing skipping table
    {
        String[] columns = new String[] { "c1 VARCHAR(5)" };
        Object[] row1 = new Object[] { "123" };
        String validOutput1 = "";
        Object[] row2 = new Object[] { null };
        String validOutput2 = "(NULL);";
        Object[] values = new Object[] { row1, row2 };
        String[] validOutput = new String[] { validOutput1, validOutput2 };

        result.add(new Object[] { "testSkip", null, columns, values, validOutput, true, false });
    }

    //testing renaming table
    {
        String[] columns = new String[] { "c1 VARCHAR(5)" };
        Object[] row1 = new Object[] { "123" };
        String validOutput1 = "('123'),";
        Object[] row2 = new Object[] { null };
        String validOutput2 = "(NULL);";
        Object[] values = new Object[] { row1, row2 };
        String[] validOutput = new String[] { validOutput1, validOutput2 };

        result.add(new Object[] { "testRename", "testRenameNew", columns, values, validOutput, false, false });
    }

    //testing empty table
    {
        String[] columns = new String[] { "c1 VARCHAR(5)" };
        Object[] values = new Object[] { new Object[] {} };
        String[] validOutput = new String[] {};

        result.add(new Object[] { "testEmptyTable", null, columns, values, validOutput, true, false });
    }

    //testing truncate table
    {
        String[] columns = new String[] { "c1 VARCHAR(5)" };
        Object[] values = new Object[] { new Object[] {} };
        String[] validOutput = new String[] {};

        result.add(new Object[] { "testTruncateTable", null, columns, values, validOutput, true, true });
    }

    return result;
}

From source file:CalendarUtils.java

/**
 * This constructs an Iterator that will start and stop over a date
 * range based on the focused date and the range style.  For instance,
 * passing Thursday, July 4, 2002 and a RANGE_MONTH_SUNDAY will return
 * an Iterator that starts with Sunday, June 30, 2002 and ends with
 * Saturday, August 3, 2002./*from   w  w w.ja  v a 2s .c o m*/
 */
public static Iterator getCalendarIterator(Calendar focus, int rangeStyle) {
    Calendar start = null;
    Calendar end = null;
    int startCutoff = Calendar.SUNDAY;
    int endCutoff = Calendar.SATURDAY;
    switch (rangeStyle) {
    case RANGE_MONTH_SUNDAY:
    case RANGE_MONTH_MONDAY:
        //Set start to the first of the month
        start = trunc(focus, Calendar.MONTH);
        //Set end to the last of the month
        end = (Calendar) start.clone();
        end.add(Calendar.MONTH, 1);
        end.add(Calendar.DATE, -1);
        //Loop start back to the previous sunday or monday
        if (rangeStyle == RANGE_MONTH_MONDAY) {
            startCutoff = Calendar.MONDAY;
            endCutoff = Calendar.SUNDAY;
        }
        break;
    case RANGE_WEEK_SUNDAY:
    case RANGE_WEEK_MONDAY:
    case RANGE_WEEK_RELATIVE:
    case RANGE_WEEK_CENTER:
        //Set start and end to the current date
        start = trunc(focus, Calendar.DATE);
        end = trunc(focus, Calendar.DATE);
        switch (rangeStyle) {
        case RANGE_WEEK_SUNDAY:
            //already set by default
            break;
        case RANGE_WEEK_MONDAY:
            startCutoff = Calendar.MONDAY;
            endCutoff = Calendar.SUNDAY;
            break;
        case RANGE_WEEK_RELATIVE:
            startCutoff = focus.get(Calendar.DAY_OF_WEEK);
            endCutoff = startCutoff - 1;
            break;
        case RANGE_WEEK_CENTER:
            startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3;
            endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3;
            break;
        }
        break;
    default:
        throw new RuntimeException("The range style " + rangeStyle + " is not valid.");
    }
    if (startCutoff < Calendar.SUNDAY) {
        startCutoff += 7;
    }
    if (endCutoff > Calendar.SATURDAY) {
        endCutoff -= 7;
    }
    while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) {
        start.add(Calendar.DATE, -1);
    }
    while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) {
        end.add(Calendar.DATE, 1);
    }
    final Calendar startFinal = start;
    final Calendar endFinal = end;
    Iterator it = new Iterator() {
        Calendar spot = null;
        {
            spot = startFinal;
            spot.add(Calendar.DATE, -1);
        }

        public boolean hasNext() {
            return spot.before(endFinal);
        }

        public Object next() {
            if (spot.equals(endFinal)) {
                throw new NoSuchElementException();
            }
            spot.add(Calendar.DATE, 1);
            return spot.clone();
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
    return it;
}

From source file:Main.java

/**
 * This constructs an <code>Iterator</code> over each day in a date
 * range defined by a focus date and range style.
 *
 * For instance, passing Thursday, July 4, 2002 and a
 * <code>RANGE_MONTH_SUNDAY</code> will return an <code>Iterator</code>
 * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
 * 2002, returning a Calendar instance for each intermediate day.
 *
 * This method provides an iterator that returns Calendar objects.
 * The days are progressed using {@link Calendar#add(int, int)}.
 *
 * @param focus  the date to work with/*www.  j av a2s .c om*/
 * @param rangeStyle  the style constant to use. Must be one of
 * {@link DateUtils#RANGE_MONTH_SUNDAY}, 
 * {@link DateUtils#RANGE_MONTH_MONDAY},
 * {@link DateUtils#RANGE_WEEK_SUNDAY},
 * {@link DateUtils#RANGE_WEEK_MONDAY},
 * {@link DateUtils#RANGE_WEEK_RELATIVE},
 * {@link DateUtils#RANGE_WEEK_CENTER}
 * @return the date iterator
 * @throws IllegalArgumentException if the date is <code>null</code>
 * @throws IllegalArgumentException if the rangeStyle is invalid
 */
public static Iterator iterator(Calendar focus, int rangeStyle) {
    if (focus == null) {
        throw new IllegalArgumentException("The date must not be null");
    }
    Calendar start = null;
    Calendar end = null;
    int startCutoff = Calendar.SUNDAY;
    int endCutoff = Calendar.SATURDAY;
    switch (rangeStyle) {
    case RANGE_MONTH_SUNDAY:
    case RANGE_MONTH_MONDAY:
        //Set start to the first of the month
        start = truncate(focus, Calendar.MONTH);
        //Set end to the last of the month
        end = (Calendar) start.clone();
        end.add(Calendar.MONTH, 1);
        end.add(Calendar.DATE, -1);
        //Loop start back to the previous sunday or monday
        if (rangeStyle == RANGE_MONTH_MONDAY) {
            startCutoff = Calendar.MONDAY;
            endCutoff = Calendar.SUNDAY;
        }
        break;
    case RANGE_WEEK_SUNDAY:
    case RANGE_WEEK_MONDAY:
    case RANGE_WEEK_RELATIVE:
    case RANGE_WEEK_CENTER:
        //Set start and end to the current date
        start = truncate(focus, Calendar.DATE);
        end = truncate(focus, Calendar.DATE);
        switch (rangeStyle) {
        case RANGE_WEEK_SUNDAY:
            //already set by default
            break;
        case RANGE_WEEK_MONDAY:
            startCutoff = Calendar.MONDAY;
            endCutoff = Calendar.SUNDAY;
            break;
        case RANGE_WEEK_RELATIVE:
            startCutoff = focus.get(Calendar.DAY_OF_WEEK);
            endCutoff = startCutoff - 1;
            break;
        case RANGE_WEEK_CENTER:
            startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3;
            endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3;
            break;
        }
        break;
    default:
        throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid.");
    }
    if (startCutoff < Calendar.SUNDAY) {
        startCutoff += 7;
    }
    if (startCutoff > Calendar.SATURDAY) {
        startCutoff -= 7;
    }
    if (endCutoff < Calendar.SUNDAY) {
        endCutoff += 7;
    }
    if (endCutoff > Calendar.SATURDAY) {
        endCutoff -= 7;
    }
    while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) {
        start.add(Calendar.DATE, -1);
    }
    while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) {
        end.add(Calendar.DATE, 1);
    }
    return new DateIterator(start, end);
}

From source file:fr.paris.lutece.plugins.calendar.service.XMLUtils.java

/**
 * Get the XML of a calendar/*from  w  w  w  .  j  av  a  2  s  .c om*/
 * @param local The locale
 * @param cal The calendar
 * @param request The request
 * @return The XML
 */
public static String getXMLPortletCalendar(Locale local, Calendar cal, HttpServletRequest request) {
    StringBuffer strXml = new StringBuffer();

    String strDay = null;
    Calendar calendar = new GregorianCalendar();

    //Set the calendar in the beginning of the month
    calendar.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1);

    int nDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

    //If day of week is sunday: nDayOfWeek = 8
    if (nDayOfWeek == 1) {
        nDayOfWeek = 8;
    }

    Calendar calendar2 = new GregorianCalendar();
    calendar2.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), calendar.getMaximum(Calendar.DAY_OF_MONTH));

    //Beginning of the main xml block: month
    XmlUtil.beginElement(strXml, TAG_AGENDA_MONTH);

    String strBaseUrl = AppPathService.getPortalUrl();

    UrlItem urlMonth = new UrlItem(strBaseUrl);
    urlMonth.addParameter(Constants.PARAMETER_PAGE, Constants.PLUGIN_NAME);
    urlMonth.addParameter(Constants.PARAMETER_ACTION, Constants.ACTION_DO_SEARCH);

    urlMonth.addParameter(Constants.PARAMETER_DATE_START, DateUtil.getDateString(calendar.getTime(), local));
    urlMonth.addParameter(Constants.PARAMETER_DATE_END, DateUtil.getDateString(calendar2.getTime(), local));
    urlMonth.addParameter(Constants.PARAMETER_PERIOD, Constants.PROPERTY_PERIOD_RANGE);

    String strMonthLabel = Utils.getMonthLabel(Utils.getDate(calendar), local);

    String strUrlMonth = BEGIN_A_TAG + urlMonth.getUrl() + "\">" + strMonthLabel + END_A_TAG;

    XmlUtil.addElementHtml(strXml, TAG_AGENDA_MONTH_LABEL, strUrlMonth);

    //Shortcut tags
    //Begenning of the xml block: week-shortcuts
    XmlUtil.beginElement(strXml, TAG_WEEK_SHORTCUTS);

    //Today shortcut 
    XmlUtil.beginElement(strXml, TAG_WEEK_SHORTCUT);
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTCUT_TODAY, local));
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_PERIOD, Constants.PROPERTY_PERIOD_TODAY);
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_DATE_START, DateUtil.getDateString(new Date(), local));
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_DATE_END, DateUtil.getDateString(new Date(), local));
    XmlUtil.endElement(strXml, TAG_WEEK_SHORTCUT);

    //Tomorrow shortcut 
    Calendar calTomorrow = new GregorianCalendar();
    calTomorrow.add(Calendar.DATE, 1);
    XmlUtil.beginElement(strXml, TAG_WEEK_SHORTCUT);
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTCUT_TOMORROW, local));
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_PERIOD, Constants.PROPERTY_PERIOD_RANGE);
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_DATE_START,
            DateUtil.getDateString(calTomorrow.getTime(), local));
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_DATE_END,
            DateUtil.getDateString(calTomorrow.getTime(), local));
    XmlUtil.endElement(strXml, TAG_WEEK_SHORTCUT);

    //Week shortcut
    Date dateBeginWeek = null;
    Date dateEndWeek = null;

    Calendar calendarToday = new GregorianCalendar();
    Calendar calendarFirstDay = Calendar.getInstance();
    Calendar calendarLastDay = new GregorianCalendar();

    calendarFirstDay = calendarToday;
    calendarFirstDay.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    calendarLastDay = (GregorianCalendar) calendarFirstDay.clone();
    calendarLastDay.add(Calendar.DATE, 6);
    dateBeginWeek = calendarFirstDay.getTime();
    dateEndWeek = calendarLastDay.getTime();

    XmlUtil.beginElement(strXml, TAG_WEEK_SHORTCUT);
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTCUT_WEEK, local));
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_PERIOD, Constants.PROPERTY_PERIOD_WEEK);
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_DATE_START, DateUtil.getDateString(dateBeginWeek, local));
    XmlUtil.addElement(strXml, TAG_WEEK_SHORTCUT_DATE_END, DateUtil.getDateString(dateEndWeek, local));
    XmlUtil.endElement(strXml, TAG_WEEK_SHORTCUT);

    //Ending of the xml block: week-shortcuts
    XmlUtil.endElement(strXml, TAG_WEEK_SHORTCUTS);

    //Begenning of the xml block: weeks
    XmlUtil.beginElement(strXml, TAG_AGENDA_WEEKS);

    //Day label tags
    XmlUtil.addElement(strXml, TAG_AGENDA_DAY_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTLABEL_MONDAY, local));
    XmlUtil.addElement(strXml, TAG_AGENDA_DAY_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTLABEL_TUESDAY, local));
    XmlUtil.addElement(strXml, TAG_AGENDA_DAY_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTLABEL_WEDNESDAY, local));
    XmlUtil.addElement(strXml, TAG_AGENDA_DAY_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTLABEL_THURSDAY, local));
    XmlUtil.addElement(strXml, TAG_AGENDA_DAY_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTLABEL_FRIDAY, local));
    XmlUtil.addElement(strXml, TAG_AGENDA_DAY_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTLABEL_SATURDAY, local));
    XmlUtil.addElement(strXml, TAG_AGENDA_DAY_LABEL,
            I18nService.getLocalizedString(Constants.PROPERTY_SHORTLABEL_SUNDAY, local));

    //Check if the month is ended
    boolean bDone = false;

    //check if the month is started
    boolean bStarted = false;

    //While the month isn't over...
    while (!bDone) {
        //Begenning of the xml block: week
        XmlUtil.beginElement(strXml, TAG_AGENDA_WEEK);

        for (int i = 0; i < 7; i++) {
            if ((((i + 2) != nDayOfWeek) && !bStarted) || bDone) {
                XmlUtil.beginElement(strXml, TAG_AGENDA_DAY);
                strDay = BEGIN_TD_TAG + getDayClass(calendar) + ">" + PROPERTY_EMPTY_DAY + END_TD_TAG;
                XmlUtil.addElementHtml(strXml, TAG_AGENDA_DAY_CODE, strDay);
                XmlUtil.endElement(strXml, TAG_AGENDA_DAY);

                continue;
            }
            bStarted = true;

            //put parameters in the url
            UrlItem urlDay = new UrlItem(strBaseUrl);
            String strPageId = request != null ? request.getParameter(Constants.PARAMETER_PAGE_ID)
                    : StringUtils.EMPTY;
            if (StringUtils.isNotBlank(strPageId) && StringUtils.isNumeric(strPageId)) {
                urlDay.addParameter(Constants.PARAMETER_PAGE_ID, strPageId);
            }
            urlDay.addParameter(Constants.PARAMETER_DATE, DateUtil.getDateString(calendar.getTime(), local));

            //construct on url based on day
            String strUrlDay = new String();
            strUrlDay = BEGIN_A_TAG + urlDay.getUrl() + "\">"
                    + Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)) + END_A_TAG;

            XmlUtil.beginElement(strXml, TAG_AGENDA_DAY);

            Date date = Utils.getDate(Utils.getDate(calendar));
            Plugin plugin = PluginService.getPlugin(CalendarPlugin.PLUGIN_NAME);

            String[] arrayCalendarIds = Utils.getCalendarIds(request);

            List<Event> listEvent = CalendarSearchService.getInstance().getSearchResults(arrayCalendarIds, null,
                    "", date, date, plugin);
            if (listEvent.size() != 0) {
                strDay = BEGIN_TD_TAG + Constants.STYLE_CLASS_SMALLMONTH_DAY
                        + Constants.STYLE_CLASS_SUFFIX_EVENT + ">" + BEGIN_BOLD_TAG + strUrlDay + END_BOLD_TAG
                        + END_TD_TAG;
            } else {
                strDay = BEGIN_TD_TAG + getDayClass(calendar) + ">"
                        + Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)) + END_TD_TAG;
            }

            XmlUtil.addElementHtml(strXml, TAG_AGENDA_DAY_CODE, strDay);

            XmlUtil.endElement(strXml, TAG_AGENDA_DAY);

            int nDay = calendar.get(Calendar.DAY_OF_MONTH);
            calendar.roll(Calendar.DAY_OF_MONTH, true);

            int nNewDay = calendar.get(Calendar.DAY_OF_MONTH);

            if (nNewDay < nDay) {
                bDone = true;
            }
        }

        //Ending of the xml block: week
        XmlUtil.endElement(strXml, TAG_AGENDA_WEEK);
    }

    //Ending of the xml block: weeks
    XmlUtil.endElement(strXml, TAG_AGENDA_WEEKS);

    //Ending of the xml block: month
    XmlUtil.endElement(strXml, TAG_AGENDA_MONTH);

    return strXml.toString();
}

From source file:com.glaf.core.util.DateUtils.java

/**
 * ?//from  ww  w  .  j a v a2 s.co m
 * 
 * @param startDate
 * @param endDate
 * @return
 */
public static int getDaysBetween(Calendar startDate, Calendar endDate) {
    if (startDate.after(endDate)) {
        java.util.Calendar swap = startDate;
        startDate = endDate;
        endDate = swap;
    }
    int days = endDate.get(java.util.Calendar.DAY_OF_YEAR) - startDate.get(java.util.Calendar.DAY_OF_YEAR);
    int y2 = endDate.get(java.util.Calendar.YEAR);
    if (startDate.get(java.util.Calendar.YEAR) != y2) {
        startDate = (java.util.Calendar) startDate.clone();
        do {
            days += startDate.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
            startDate.add(java.util.Calendar.YEAR, 1);
        } while (startDate.get(java.util.Calendar.YEAR) != y2);
    }
    return days;
}