Java Code Examples for java.util.Calendar#clone()

The following examples show how to use java.util.Calendar#clone() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TimeUtils.java    From OmniList with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 获取指定月份的开始和截止的毫秒数:比如2017年5月,获取的是
 * 2017年5月1日0:0:0 0'的毫秒数和2017年5月31日23:59:59 999'的毫秒数
 *
 * @param year 年
 * @param month 1代表1月
 * @return 开始和截止的毫秒数 */
public static long[] getStartAndEndMillisOfMonth(int year, int month){
    Calendar startTime = Calendar.getInstance();
    startTime.set(Calendar.YEAR, year);
    startTime.set(Calendar.MONTH, month - 1);
    startTime.set(Calendar.DAY_OF_MONTH, 1);
    startTime.set(Calendar.HOUR_OF_DAY, 0);
    startTime.set(Calendar.MINUTE, 0);
    startTime.set(Calendar.SECOND, 0);
    startTime.set(Calendar.MILLISECOND, 0);

    int daysOfMonth = getDaysOfMonth(year, month);
    Calendar endTime = (Calendar) startTime.clone();
    endTime.add(Calendar.DAY_OF_MONTH, daysOfMonth);
    return new long[]{startTime.getTimeInMillis(), endTime.getTimeInMillis() - 1};
}
 
Example 2
Source File: CalendarModifiedFollowingHandler.java    From objectlabkit with Apache License 2.0 6 votes vote down vote up
public Calendar adjustDate(final Calendar startDate, final int increment, final NonWorkingDayChecker<Calendar> checker) {
    final Calendar cal = (Calendar) startDate.clone();
    int step = increment;
    final int month = cal.get(Calendar.MONTH);

    while (checker.isNonWorkingDay(cal)) {
        cal.add(Calendar.DAY_OF_MONTH, step);
        if (month != cal.get(Calendar.MONTH)) {
            // switch direction and go back
            step *= -1;
            cal.add(Calendar.DAY_OF_MONTH, step);
        }
    }

    return cal;
}
 
Example 3
Source File: Week.java    From opensim-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the first millisecond of the week, evaluated using the supplied
 * calendar (which determines the time zone).
 *
 * @param calendar  the calendar (<code>null</code> not permitted).
 *
 * @return The first millisecond of the week.
 *
 * @throws NullPointerException if <code>calendar</code> is 
 *     <code>null</code>.
 */
public long getFirstMillisecond(Calendar calendar) {
    Calendar c = (Calendar) calendar.clone();
    c.clear();
    c.set(Calendar.YEAR, this.year);
    c.set(Calendar.WEEK_OF_YEAR, this.week);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
    c.set(Calendar.HOUR, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    //return c.getTimeInMillis();  // this won't work for JDK 1.3
    return c.getTime().getTime();
}
 
Example 4
Source File: SimpleContext.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Calendar getLocalTime() {
   Calendar localTime = this.localTime;
   if(localTime == null) {
      return Calendar.getInstance();
   }
   return (Calendar) localTime.clone();
}
 
Example 5
Source File: CalendarForwardHandler.java    From objectlabkit with Apache License 2.0 5 votes vote down vote up
public Calendar adjustDate(final Calendar startDate, final int increment, final NonWorkingDayChecker<Calendar> checker) {
    final Calendar cal = (Calendar) startDate.clone();

    while (checker.isNonWorkingDay(cal)) {
        cal.add(Calendar.DAY_OF_MONTH, increment);
    }

    return cal;
}
 
Example 6
Source File: JobRequest.java    From jqm with Apache License 2.0 5 votes vote down vote up
/**
 * <strong>Optional</strong><br>
 * The default behaviour for a newly submitted JobRequest is to run as soon as possible (i.e. as soon as there is a free slot inside a
 * JQM node). This method allows to change this, and to put the request inside the queue but not run it when it reaches the top of the
 * queue. It will only be eligible for run when the given date is reached. When the given date is reached, standard queuing resumes.<br>
 * The resolution of this function is the minute: seconds and lower are ignored (truncated).<br>
 */
public JobRequest setRunAfter(Calendar whenToRun)
{
    this.runAfter = (Calendar) whenToRun.clone();
    this.runAfter.set(Calendar.SECOND, 0);
    this.runAfter.set(Calendar.MILLISECOND, 0);
    return this;
}
 
Example 7
Source File: Elixir_005_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Returns the last millisecond of the week, evaluated using the supplied
 * calendar (which determines the time zone).
 *
 * @param calendar  the calendar (<code>null</code> not permitted).
 *
 * @return The last millisecond of the week.
 *
 * @throws NullPointerException if <code>calendar</code> is
 *     <code>null</code>.
 */
public long getLastMillisecond(Calendar calendar) {
    Calendar c = (Calendar) calendar.clone();
    c.clear();
    c.set(Calendar.YEAR, this.year);
    c.set(Calendar.WEEK_OF_YEAR, this.week + 1);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
    c.set(Calendar.HOUR, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    //return c.getTimeInMillis();  // this won't work for JDK 1.3
    return c.getTime().getTime() - 1;
}
 
Example 8
Source File: DateUtilsTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This checks that this is a 7 element iterator of Calendar objects
 * that are dates (no time), and exactly 1 day spaced after each other.
 */
private static void assertWeekIterator(final Iterator<?> it, final Calendar start) {
    final Calendar end = (Calendar) start.clone();
    end.add(Calendar.DATE, 6);

    assertWeekIterator(it, start, end);
}
 
Example 9
Source File: Elixir_005_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Returns the first millisecond of the week, evaluated using the supplied
 * calendar (which determines the time zone).
 *
 * @param calendar  the calendar (<code>null</code> not permitted).
 *
 * @return The first millisecond of the week.
 *
 * @throws NullPointerException if <code>calendar</code> is
 *     <code>null</code>.
 */
public long getFirstMillisecond(Calendar calendar) {
    Calendar c = (Calendar) calendar.clone();
    c.clear();
    c.set(Calendar.YEAR, this.year);
    c.set(Calendar.WEEK_OF_YEAR, this.week);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
    c.set(Calendar.HOUR, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    //return c.getTimeInMillis();  // this won't work for JDK 1.3
    return c.getTime().getTime();
}
 
Example 10
Source File: TestScheduler.java    From vertx-scheduler with Apache License 2.0 5 votes vote down vote up
private boolean closeEnough(Calendar target, Calendar actual) {
    final Logger log = container.logger();
    log.info("Checking that " + target.getTime().toString() + " and " + actual.getTime().toString() + " are very close");
    Calendar end = (Calendar)target.clone();
    end.add(Calendar.SECOND, 1);
    return actual.after(target) && actual.before(end);
}
 
Example 11
Source File: DurationImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>Converts the years and months fields into the days field
 * by using a specific time instant as the reference point.</p>
 *
 * <p>For example, duration of one month normalizes to 31 days
 * given the start time instance "July 8th 2003, 17:40:32".</p>
 *
 * <p>Formally, the computation is done as follows:</p>
 * <ol>
 *  <li>The given Calendar object is cloned.
 *  <li>The years, months and days fields will be added to
 *      the {@link Calendar} object
 *      by using the {@link Calendar#add(int,int)} method.
 *  <li>The difference between two Calendars are computed in terms of days.
 *  <li>The computed days, along with the hours, minutes and seconds
 *      fields of this duration object is used to construct a new
 *      Duration object.
 * </ol>
 *
 * <p>Note that since the Calendar class uses <code>int</code> to
 * hold the value of year and month, this method may produce
 * an unexpected result if this duration object holds
 * a very large value in the years or months fields.</p>
 *
 * @param startTimeInstant <code>Calendar</code> reference point.
 *
 * @return <code>Duration</code> of years and months of this <code>Duration</code> as days.
 *
 * @throws NullPointerException If the startTimeInstant parameter is null.
 */
public Duration normalizeWith(Calendar startTimeInstant) {

    Calendar c = (Calendar) startTimeInstant.clone();

    // using int may cause overflow, but
    // Calendar internally treats value as int anyways.
    c.add(Calendar.YEAR, getYears() * signum);
    c.add(Calendar.MONTH, getMonths() * signum);
    c.add(Calendar.DAY_OF_MONTH, getDays() * signum);

    // obtain the difference in terms of days
    long diff = getCalendarTimeInMillis(c) - getCalendarTimeInMillis(startTimeInstant);
    int days = (int) (diff / (1000L * 60L * 60L * 24L));

    return new DurationImpl(
            days >= 0,
            null,
            null,
            wrap(Math.abs(days)),
            (BigInteger) getField(DatatypeConstants.HOURS),
            (BigInteger) getField(DatatypeConstants.MINUTES),
            (BigDecimal) getField(DatatypeConstants.SECONDS));
}
 
Example 12
Source File: SegmentedTimelineTest.java    From openstock with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Sets up the fixture, for example, open a network connection.
 * This method is called before a test is executed.
 *
 * @throws Exception if there is a problem.
 */
@Before
public void setUp() throws Exception {
    // setup our test timelines
    //
    // Legend for comments below:
    // <spaces> = Segments included in the final timeline
    // EE       = Excluded segments via timeline rules
    // xx       = Exception segments inherited from base timeline exclusions

    // 1-ms test timeline using 5 included and 2 excluded segments.
    //
    // timeline start time = 0
    //   |
    //   v
    //   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 ..
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+..
    // |  |  |  |  |  |EE|EE|  |  |  |  |  |EE|EE|  |  |  |  |  |  |EE|EE|    <-- msTimeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+..
    //  \_________  ________/            \_/
    //            \/                      |
    //       segment group         segment size = 1 ms
    //
    this.msTimeline = new SegmentedTimeline(1, 5, 2);
    this.msTimeline.setStartTime(0);

    // 4-ms test base timeline for ms2Timeline using 1 included and 1
    // excluded segments
    //
    // timeline start time = 0
    //   |
    //   v
    //   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 ...
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    // |  |  |  |  |EE|EE|EE|EE|  |  |  |  |EE|EE|EE|EE|  |  |  |  |    <-- ms2BaseTimeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    //  \__________  _________/            \____  _____/
    //             \/                           \/
    //        segment group              segment size = 4 ms
    //
    this.ms2BaseTimeline = new SegmentedTimeline(4, 1, 1);
    this.ms2BaseTimeline.setStartTime(0);

    // 1-ms test timeline (with a baseTimeline) using 2 included and 2
    // excluded segments centered inside each base segment
    //
    // The ms2Timeline without a base would look like this:
    //
    //    timeline start time = 1
    //      |
    //      v
    //   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 ...
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    // |EE|  |  |EE|EE|  |  |EE|EE|  |  |EE|EE|  |  |EE|EE|  |  |EE|    <-- ms2Timeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    //    \____  _____/            \_/
    //         \/                   |
    //    segment group      segment size = 1 ms
    //
    // With the base timeline some originally included segments are now
    // removed (see "xx" below):
    //
    //   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 ...
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    // |EE|  |  |EE|EE|xx|xx|EE|EE|  |  |EE|EE|xx|xx|EE|EE|  |  |EE|    <-- ms2Timeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    // |  |  |  |  |EE|EE|EE|EE|  |  |  |  |EE|EE|EE|EE|  |  |  |  |    <-- ms2BaseTimeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    //
    this.ms2Timeline = new SegmentedTimeline(1, 2, 2);
    this.ms2Timeline.setStartTime(1);
    this.ms2Timeline.setBaseTimeline(this.ms2BaseTimeline);

    // test monday though friday timeline
    this.mondayFridayTimeline
            = SegmentedTimeline.newMondayThroughFridayTimeline();

    // test 9am-4pm Monday through Friday timeline
    this.fifteenMinTimeline
            = SegmentedTimeline.newFifteenMinuteTimeline();

    // find first Monday after 2001-01-01
    Calendar cal = new GregorianCalendar(
            SegmentedTimeline.NO_DST_TIME_ZONE);
    cal.set(2001, 0, 1, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        cal.add(Calendar.DATE, 1);
    }
    this.monday = (Calendar) cal.clone();

    // calculate 9am on the first Monday after 2001-01-01
    cal.add(Calendar.HOUR, 9);
    this.monday9am = (Calendar) cal.clone();
}
 
Example 13
Source File: DateUtilities.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Calendar removeMilliseconds(Calendar calendar) {
	Calendar returnCalendar = (Calendar) calendar.clone();
	returnCalendar.set(Calendar.MILLISECOND, 0);
	return returnCalendar;
}
 
Example 14
Source File: DurationImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>Converts the years and months fields into the days field
 * by using a specific time instant as the reference point.</p>
 *
 * <p>For example, duration of one month normalizes to 31 days
 * given the start time instance "July 8th 2003, 17:40:32".</p>
 *
 * <p>Formally, the computation is done as follows:</p>
 * <ol>
 *  <li>The given Calendar object is cloned.
 *  <li>The years, months and days fields will be added to
 *      the {@link Calendar} object
 *      by using the {@link Calendar#add(int,int)} method.
 *  <li>The difference between two Calendars are computed in terms of days.
 *  <li>The computed days, along with the hours, minutes and seconds
 *      fields of this duration object is used to construct a new
 *      Duration object.
 * </ol>
 *
 * <p>Note that since the Calendar class uses <code>int</code> to
 * hold the value of year and month, this method may produce
 * an unexpected result if this duration object holds
 * a very large value in the years or months fields.</p>
 *
 * @param startTimeInstant <code>Calendar</code> reference point.
 *
 * @return <code>Duration</code> of years and months of this <code>Duration</code> as days.
 *
 * @throws NullPointerException If the startTimeInstant parameter is null.
 */
public Duration normalizeWith(Calendar startTimeInstant) {

    Calendar c = (Calendar) startTimeInstant.clone();

    // using int may cause overflow, but
    // Calendar internally treats value as int anyways.
    c.add(Calendar.YEAR, getYears() * signum);
    c.add(Calendar.MONTH, getMonths() * signum);
    c.add(Calendar.DAY_OF_MONTH, getDays() * signum);

    // obtain the difference in terms of days
    long diff = getCalendarTimeInMillis(c) - getCalendarTimeInMillis(startTimeInstant);
    int days = (int) (diff / (1000L * 60L * 60L * 24L));

    return new DurationImpl(
        days >= 0,
        null,
        null,
        wrap(Math.abs(days)),
        (BigInteger) getField(DatatypeConstants.HOURS),
        (BigInteger) getField(DatatypeConstants.MINUTES),
        (BigDecimal) getField(DatatypeConstants.SECONDS));
}
 
Example 15
Source File: CalendarUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static Calendar addDays(Calendar calendar, int days) {
   Calendar c = (Calendar) calendar.clone();
   c.add(Calendar.DAY_OF_YEAR, days);
   return c;
}
 
Example 16
Source File: DateHelper.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 当月第一天
 * @param day
 * @return
 */
public static Calendar getMonthFirstDay(Calendar day) {
    Calendar newDay = (Calendar) day.clone();
    newDay.set(Calendar.DAY_OF_MONTH, 1);
    return newDay;
}
 
Example 17
Source File: DateUtils.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * <p>Rounds a date, leaving the field specified as the most
 * significant field.</p>
 *
 * <p>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. If this was passed with MONTH, it
 * would return 1 April 2002 0:00:00.000.</p>
 * 
 * <p>For a date in a timezone that handles the change to daylight
 * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
 * Suppose daylight saving time begins at 02:00 on March 30. Rounding a 
 * date that crosses this time would produce the following values:
 * <ul>
 * <li>March 30, 2003 01:10 rounds to March 30, 2003 01:00</li>
 * <li>March 30, 2003 01:40 rounds to March 30, 2003 03:00</li>
 * <li>March 30, 2003 02:10 rounds to March 30, 2003 03:00</li>
 * <li>March 30, 2003 02:40 rounds to March 30, 2003 04:00</li>
 * </ul>
 * </p>
 * 
 * @param date  the date to work with, not null
 * @param field  the field from {@code Calendar} or <code>SEMI_MONTH</code>
 * @return the different rounded date, not null
 * @throws IllegalArgumentException if the date is <code>null</code>
 * @throws ArithmeticException if the year is over 280 million
 */
public static Calendar round(final Calendar date, final int field) {
    if (date == null) {
        throw new IllegalArgumentException("The date must not be null");
    }
    final Calendar rounded = (Calendar) date.clone();
    modify(rounded, field, MODIFY_ROUND);
    return rounded;
}
 
Example 18
Source File: Duration.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * <p>Returns the length of the duration in milli-seconds.</p>
 *
 * <p>If the seconds field carries more digits than milli-second order,
 * those will be simply discarded (or in other words, rounded to zero.)
 * For example, for any Calendar value <code>x</code>,</p>
 * <pre>
 * <code>new Duration("PT10.00099S").getTimeInMills(x) == 10000</code>.
 * <code>new Duration("-PT10.00099S").getTimeInMills(x) == -10000</code>.
 * </pre>
 *
 * <p>
 * Note that this method uses the {@link #addTo(Calendar)} method,
 * which may work incorrectly with <code>Duration</code> objects with
 * very large values in its fields. See the {@link #addTo(Calendar)}
 * method for details.
 *
 * @param startInstant
 *      The length of a month/year varies. The <code>startInstant</code> is
 *      used to disambiguate this variance. Specifically, this method
 *      returns the difference between <code>startInstant</code> and
 *      <code>startInstant+duration</code>
 *
 * @return milliseconds between <code>startInstant</code> and
 *   <code>startInstant</code> plus this <code>Duration</code>
 *
 * @throws NullPointerException if <code>startInstant</code> parameter
 * is null.
 *
 */
public long getTimeInMillis(final Calendar startInstant) {
    Calendar cal = (Calendar) startInstant.clone();
    addTo(cal);
    return getCalendarTimeInMillis(cal)
                - getCalendarTimeInMillis(startInstant);
}
 
Example 19
Source File: Duration.java    From openjdk-8-source with GNU General Public License v2.0 3 votes vote down vote up
/**
 * <p>Returns the length of the duration in milli-seconds.</p>
 *
 * <p>If the seconds field carries more digits than milli-second order,
 * those will be simply discarded (or in other words, rounded to zero.)
 * For example, for any Calendar value <code>x</code>,</p>
 * <pre>
 * <code>new Duration("PT10.00099S").getTimeInMills(x) == 10000</code>.
 * <code>new Duration("-PT10.00099S").getTimeInMills(x) == -10000</code>.
 * </pre>
 *
 * <p>
 * Note that this method uses the {@link #addTo(Calendar)} method,
 * which may work incorrectly with <code>Duration</code> objects with
 * very large values in its fields. See the {@link #addTo(Calendar)}
 * method for details.
 *
 * @param startInstant
 *      The length of a month/year varies. The <code>startInstant</code> is
 *      used to disambiguate this variance. Specifically, this method
 *      returns the difference between <code>startInstant</code> and
 *      <code>startInstant+duration</code>
 *
 * @return milliseconds between <code>startInstant</code> and
 *   <code>startInstant</code> plus this <code>Duration</code>
 *
 * @throws NullPointerException if <code>startInstant</code> parameter
 * is null.
 *
 */
public long getTimeInMillis(final Calendar startInstant) {
    Calendar cal = (Calendar) startInstant.clone();
    addTo(cal);
    return getCalendarTimeInMillis(cal)
                - getCalendarTimeInMillis(startInstant);
}
 
Example 20
Source File: DateUtils.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * <p>Truncates a date, leaving the field specified as the most
 * significant field.</p>
 *
 * <p>For example, if you had the date-time of 28 Mar 2002
 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
 * 2002 13:00:00.000.  If this was passed with MONTH, it would
 * return 1 Mar 2002 0:00:00.000.</p>
 * 
 * @param date  the date to work with, not null
 * @param field  the field from {@code Calendar} or <code>SEMI_MONTH</code>
 * @return the different truncated date, not null
 * @throws IllegalArgumentException if the date is <code>null</code>
 * @throws ArithmeticException if the year is over 280 million
 */
public static Calendar truncate(Calendar date, int field) {
    if (date == null) {
        throw new IllegalArgumentException("The date must not be null");
    }
    Calendar truncated = (Calendar) date.clone();
    modify(truncated, field, MODIFY_TRUNCATE);
    return truncated;
}