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

The following are Jave code examples for showing how to use clone() of the java.util.Calendar class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: JRediClients   File: TimeUtils.java   View Source Code Vote up 7 votes
/**
 * 以日期中的日为实际计算单位,计算两个时间点实际日的差距 比如 12-1 23:00 和12-2 01:00,相差1天,而不是小于24小时就算做0天
 * 如果(now - st)为正,则表示now在st之后
 *
 * @param st
 * @param now
 * @return
 */
public static int getSoFarWentDays(Calendar st, Calendar now) {

	int sign = st.before(now) ? 1 : -1;
	if (now.before(st)) {
		Calendar tmp = now;
		now = st;
		st = tmp;
	}
	int days = now.get(Calendar.DAY_OF_YEAR) - st.get(Calendar.DAY_OF_YEAR);
	if (st.get(Calendar.YEAR) != now.get(Calendar.YEAR)) {
		Calendar cloneSt = (Calendar) st.clone();
		while (cloneSt.get(Calendar.YEAR) != now.get(Calendar.YEAR)) {
			days += cloneSt.getActualMaximum(Calendar.DAY_OF_YEAR);
			cloneSt.add(Calendar.YEAR, 1);
		}
	}

	return days * sign;
}
 
Example 2
Project: SER316-Dresden   File: EventsTableWeekly.java   View Source Code Vote up 7 votes
public void initTable(CalendarDate d) {
	setModel(new EventsTableModel());
	int fDow = Configuration.get("FIRST_DAY_OF_WEEK").equals("mon")?Calendar.MONDAY:Calendar.SUNDAY;
	Calendar cal = d.getCalendar();
	if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY && fDow == Calendar.MONDAY) cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-6);
	else 
		cal.set(Calendar.DAY_OF_WEEK, fDow);
	Calendar changeCal = (Calendar)cal.clone();
	for(int i = 0;i<7;i++){
		changeCal.set(Calendar.DAY_OF_YEAR, i+cal.get(Calendar.DAY_OF_YEAR));
		events[i] = new Vector(EventsManager.getEventsForDate(new CalendarDate(changeCal)));
		days[i] = (Calendar)changeCal.clone();
	}
		
    for(int i = 0;i<getColumnModel().getColumnCount();i++){
    	getColumnModel().getColumn(i).setPreferredWidth(100);
        getColumnModel().getColumn(i).setMaxWidth(100);
    }
    clearSelection();
    updateUI();
}
 
Example 3
Project: boohee_v5.6   File: DailySignReceiver.java   View Source Code Vote up 7 votes
public static void start(Context ctx) {
    AlarmManager manager = (AlarmManager) ctx.getSystemService("alarm");
    PendingIntent pending = PendingIntent.getBroadcast(ctx, requestCode, new Intent(ctx,
            DailySignReceiver.class), 134217728);
    Helper.showLog(TAG, "DailySignReceiver start");
    Calendar calNow = Calendar.getInstance();
    Calendar calSet = (Calendar) calNow.clone();
    calSet.setTimeInMillis(System.currentTimeMillis());
    calSet.set(11, 12);
    calSet.set(12, 0);
    calSet.set(13, 0);
    calSet.set(14, 0);
    if (calSet.compareTo(calNow) <= 0) {
        calSet.add(5, 1);
    }
    manager.setRepeating(0, calSet.getTimeInMillis(), a.h, pending);
}
 
Example 4
Project: boohee_v5.6   File: SportRemindReceiver.java   View Source Code Vote up 7 votes
public static void start(Context ctx) {
    AlarmManager manager = (AlarmManager) ctx.getSystemService("alarm");
    PendingIntent pending = PendingIntent.getBroadcast(ctx, 152, new Intent(ctx,
            SportRemindReceiver.class), 134217728);
    Helper.showLog(TAG, "SportRemindReceiver start");
    Calendar calNow = Calendar.getInstance();
    Calendar calSet = (Calendar) calNow.clone();
    calSet.setTimeInMillis(System.currentTimeMillis());
    int remindHour = 20;
    int remindMinute = 30;
    if (!TextUtil.isEmpty(OnePreference.getPrefSportRemindTime())) {
        String[] times = OnePreference.getPrefSportRemindTime().split("#");
        if (times.length == 2) {
            remindHour = Integer.parseInt(times[0]);
            remindMinute = Integer.parseInt(times[1]);
        }
    }
    calSet.set(11, remindHour);
    calSet.set(12, remindMinute);
    calSet.set(13, 0);
    calSet.set(14, 0);
    if (calSet.compareTo(calNow) <= 0) {
        calSet.add(5, 1);
    }
    manager.setRepeating(0, calSet.getTimeInMillis(), a.h, pending);
}
 
Example 5
Project: JRediClients   File: TimeUtils.java   View Source Code Vote up 6 votes
public static int getSoFarWentHours(long time1, long time2) {
	Calendar st = Calendar.getInstance();
	st.setTimeInMillis(time1);

	Calendar now = Calendar.getInstance();
	now.setTimeInMillis(time2);


	if (now.before(st)) {
		Calendar tmp = now;
		now = st;
		st = tmp;
	}

	st.clear(Calendar.MILLISECOND);
	st.clear(Calendar.SECOND);
	st.clear(Calendar.MINUTE);

	int diffHour = 0;
	Calendar cloneSt = (Calendar) st.clone();
	while(cloneSt.before(now))
	{
		cloneSt.add(Calendar.HOUR, 1);
		diffHour++;
	}

	if(diffHour != 0)
	{
		return diffHour - 1;
	}
	else
	{
		return diffHour;
	}
}
 
Example 6
Project: otter-G   File: AbstractRuleMonitor.java   View Source Code Vote up 6 votes
protected boolean isAfter(Calendar now, String time) {
    String[] hourAndMin = StringUtils.split(time, ":");
    if (hourAndMin == null || hourAndMin.length != 2) {
        log.error("error period time format in rule : " + time);
        return isInPeriodWhenErrorFormat();
    }

    int hour;
    int min;
    try {
        hour = Integer.parseInt(hourAndMin[0]);
        min = Integer.parseInt(hourAndMin[1]);
    } catch (NumberFormatException e) {
        log.error("error period time format in rule : " + time, e);
        return isInPeriodWhenErrorFormat();
    }

    if (hour > 24 || min > 60) {
        log.error("error period time format in rule : " + time);
        return isInPeriodWhenErrorFormat();
    }

    Calendar when = (Calendar) now.clone();
    when.set(Calendar.HOUR_OF_DAY, hour);
    when.set(Calendar.MINUTE, min);

    return !now.before(when);
}
 
Example 7
Project: TechnicalAnalysisTool   File: DateUtil.java   View Source Code Vote up 6 votes
/**
 * Return if the date is the last Day of the month
 * @param calendar Calendar object in query
 * @param countryName the country name
 * @return true if it is otherwise return false
 */
public static boolean isLastDayofWeek(Calendar calendar, String countryName){
    
    Calendar local =  (Calendar)calendar.clone();
    
    if(local == null)
        return false;

    //If it is Friday
    if(local.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY){
        if (isPublicHoliday(local, countryName)){
            return false;
        }else{
            return true;
        }
    }else{
        if (isPublicHoliday(local,countryName)){
            return false;
        }else{
            while(local.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY){
                local.add(Calendar.DAY_OF_WEEK, 1);
                if (!isWeekend(local) && !isPublicHoliday(local, countryName)){
                    return false;
                }
            }
            //Check the last day of the month is the public holiday or not
            if (!isWeekend(local) && !isPublicHoliday(local,countryName)){
                return false;
            } else {
                return true;
            }
        }
    }
}
 
Example 8
Project: Material-Calendar-View   File: DateUtils.java   View Source Code Vote up 6 votes
/**
 * This method compares calendars using month and year
 *
 * @param firstCalendar  First calendar object to compare
 * @param secondCalendar Second calendar object to compare
 * @return Boolean value if second calendar is after the first one
 */
public static boolean isMonthAfter(Calendar firstCalendar, Calendar secondCalendar) {
    if (firstCalendar == null) {
        return false;
    }

    Calendar firstDay = (Calendar) firstCalendar.clone();
    setMidnight(firstDay);
    firstDay.set(Calendar.DAY_OF_MONTH, 1);
    Calendar secondDay = (Calendar) secondCalendar.clone();
    setMidnight(secondDay);
    secondDay.set(Calendar.DAY_OF_MONTH, 1);

    return secondDay.after(firstDay);
}
 
Example 9
Project: Planchester   File: DateHelper.java   View Source Code Vote up 6 votes
/**
 * @param  dayOfWeek            date in the week you would like to get the start date from
 * @param  weekStartDayIndex    index of the day the weeks starts at. ATTENTION: sunday = 1, monday = 2, ...
 * @return                      date of the first day of week
 */
public static Calendar getStartOfWeek(Calendar dayOfWeek, int weekStartDayIndex) {
    Calendar startDay = (Calendar) dayOfWeek.clone();
    while (startDay.get(Calendar.DAY_OF_WEEK) != weekStartDayIndex) {
        startDay.add(Calendar.DATE, -1);
    }
    startDay.set(Calendar.HOUR_OF_DAY, 0);
    startDay.set(Calendar.MINUTE, 00);
    startDay.set(Calendar.SECOND, 00);
    startDay.set(Calendar.MILLISECOND, 000);
    return startDay;
}
 
Example 10
Project: JRediClients   File: TimeUtils.java   View Source Code Vote up 5 votes
/**
 * 得到从time1 到time2 中,specTime所指定的时分秒的时刻,有几次
 * @param time1
 * @param time2
 * @param specTime
 * @return
 */
public static int getSpecTimeCountBetween(long time1, long time2, long specTime)
{
	Calendar st = Calendar.getInstance();
	st.setTimeInMillis(time1);

	Calendar now = Calendar.getInstance();
	now.setTimeInMillis(time2);

	Calendar spec = Calendar.getInstance();
	spec.setTimeInMillis(specTime);

	if (now.before(st)) {
		Calendar tmp = now;
		now = st;
		st = tmp;
	}

	//第一个时间的年月日和被比较时间的时间部分合成
	Calendar st_spec = mergeDateAndTime(st,spec);

	if(isSameDay(time1, time2))
	{
		if(hasSpecTimeBetween(time1,time2,st_spec.getTimeInMillis()))
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}

	int diffDay = 0;
	Calendar cloneSt = (Calendar) st_spec.clone();
	while(cloneSt.before(now))
	{
		cloneSt.add(Calendar.DATE, 1);
		diffDay++;
	}

	if(st.after(st_spec))
	{
		diffDay--;
	}

	return diffDay;
}
 
Example 11
Project: MyCalendar   File: AddEditWeekLessonDialogFragment.java   View Source Code Vote up 5 votes
private void onBeforeShowDatePicker(int view_id, Calendar cal) {
    mViewId = view_id;
    mActiveCal = (Calendar) cal.clone();
}
 
Example 12
Project: vos_instagram_bots   File: CityBot.java   View Source Code Vote up 5 votes
/**
 * Constructor - CityBot
 * @param startCalendar
 * @param airportCode
 * @param latitude
 * @param longitude
 * @param populationInMillions
 * @param addedYearMonthDay
 * @return new CityBot Object
 * @throws Exception
 */
public CityBot (
  Calendar startCalendar,
  String airportCode,
  double latitude,
  double longitude,
  int populationInMillions,
  String addedYearMonthDay) throws Exception {
  
  super(
    "city_bot",
    PeriodicJob.Type.ASYNC,
    startCalendar,
    new Period(
      1.0,
      TimeUnitType.DAY),
    new CycleTickerBuilder()
      .runFor(new Period(1, TimeUnitType.YEAR) )
      .build() );
  
  this.startCalendar = (Calendar)startCalendar.clone();
  
  this.airportCode = airportCode;
  this.latitude = latitude;
  this.longitude = longitude;
  this.populationInMillions = populationInMillions;
  
  this.addedYearMonthDay = addedYearMonthDay;
  this.addedDate = Calendar.getInstance();
  
  String[] addedDateParts = addedYearMonthDay.split("_");
  
  this.addedDate.set(
    Integer.parseInt(addedDateParts[0] ),
    Integer.parseInt(addedDateParts[1] ),
    Integer.parseInt(addedDateParts[2] ) );
  
  this.currentCalendar = CalendarAndDateOperationsInl.getCurrentCalendar();
  this.yesterdayCalendar = (Calendar)this.currentCalendar.clone();
  this.yesterdayCalendar.add(Calendar.DATE, -1);
  this.lastWeekCalendar = (Calendar)this.currentCalendar.clone();
  this.lastWeekCalendar.add(Calendar.DATE, -6);
  this.startTillYesterdayCalendars =
    CalendarAndDateOperationsInl.getCalendarsFromTo(
      this.startCalendar,
      this.yesterdayCalendar);
  this.lastWeekTillYesterdayCalendars =
    CalendarAndDateOperationsInl.getCalendarsFromTo(
      this.lastWeekCalendar,
      this.yesterdayCalendar);
  this.lastWeekTillTodayCalendars =
    CalendarAndDateOperationsInl.getCalendarsFromTo(
      this.lastWeekCalendar,
      this.currentCalendar);
  this.weekCount =
    CalendarAndDateOperationsInl.getWeekCalendarsRanges(
      this.startCalendar,
      this.currentCalendar).size();
}
 
Example 13
Project: appinventor-extensions   File: Clock.java   View Source Code Vote up 5 votes
@SimpleFunction(description = "An instant in time some hours after the argument")
public static Calendar AddHours(Calendar instant, int quantity) {
  Calendar newInstant = (Calendar) instant.clone();
  Dates.DateAdd(newInstant, Calendar.HOUR_OF_DAY, quantity);
  return newInstant;
}
 
Example 14
Project: appinventor-extensions   File: Clock.java   View Source Code Vote up 5 votes
@SimpleFunction(description = "An instant in time some minutes after the argument")
public static Calendar AddMinutes(Calendar instant, int quantity) {
  Calendar newInstant = (Calendar) instant.clone();
  Dates.DateAdd(newInstant, Calendar.MINUTE, quantity);
  return newInstant;
}
 
Example 15
Project: neoscada   File: QueryBufferTest.java   View Source Code Vote up 5 votes
private Date timestamp ( final Calendar base, final int addSeconds )
{
    final Calendar c = (Calendar)base.clone ();
    c.add ( Calendar.SECOND, addSeconds );
    return c.getTime ();
}
 
Example 16
Project: neoscada   File: QueryBufferTest.java   View Source Code Vote up 5 votes
private Date timestampMs ( final Calendar base, final int ms )
{
    final Calendar c = (Calendar)base.clone ();
    c.add ( Calendar.MILLISECOND, ms );
    return c.getTime ();
}
 
Example 17
Project: appinventor-extensions   File: Clock.java   View Source Code Vote up 5 votes
@SimpleFunction(description = "An instant in time some years after the argument")
public static Calendar AddYears(Calendar instant, int quantity) {
  Calendar newInstant = (Calendar) instant.clone();
  Dates.DateAdd(newInstant, Calendar.YEAR, quantity);
  return newInstant;
}
 
Example 18
Project: openjdk-jdk10   File: DurationImpl.java   View Source Code Vote up 5 votes
/**
 * <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 19
Project: OpenJSharp   File: DurationImpl.java   View Source Code Vote up 4 votes
/**
 * <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 incorectly with {@link Duration} 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
Project: java-learn   File: DateUtilsPartMethod.java   View Source Code Vote up 4 votes
/**
     * <p>Gets a date ceiling, 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 14:00:00.000.  If this was passed with MONTH, it would
     * return 1 Apr 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 ceil date, not null
     * @throws IllegalArgumentException if the date is <code>null</code>
     * @throws ArithmeticException if the year is over 280 million
     * @since 2.5
     */
    public static Calendar ceiling(final Calendar date, final int field) {

        if (date == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        final Calendar ceiled = (Calendar) date.clone();

//        modify(ceiled, field, DateUtils.ModifyType.CEILING);
        return ceiled;
    }