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

The following examples show how to use java.util.Calendar#equals() . 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: DateUtil.java    From maven-archetype with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 判断当前是否在指定时间之后1天,按自然日计算
 * @param date
 * @return
 */
public static boolean isAurrentAfterDay1(Date date){
	Calendar cal=Calendar.getInstance();
	cal.setTime(date);
	cal.set(Calendar.HOUR_OF_DAY, 0);
	cal.set(Calendar.MINUTE, 0);
	cal.set(Calendar.SECOND, 0);
	cal.set(Calendar.MILLISECOND, 0);
	cal.add(Calendar.DAY_OF_MONTH, 1);
	Calendar current=Calendar.getInstance();
	current.set(Calendar.HOUR_OF_DAY, 0);
	current.set(Calendar.MINUTE, 0);
	current.set(Calendar.SECOND, 0);
	current.set(Calendar.MILLISECOND, 0);
	return current.equals(cal);
}
 
Example 2
Source File: DateRangeRules.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Range<Calendar> ceilRange(TimeUnitRange timeUnit, SqlKind comparison,
    Calendar c) {
  final Calendar ceil = ceil(c, timeUnit);
  boolean boundary = ceil.equals(c);
  switch (comparison) {
  case EQUALS:
    return Range.openClosed(boundary ? decrement(ceil, timeUnit) : ceil, ceil);
  case LESS_THAN:
    return Range.atMost(decrement(ceil, timeUnit));
  case LESS_THAN_OR_EQUAL:
    return boundary ? Range.atMost(ceil) : Range.atMost(decrement(ceil, timeUnit));
  case GREATER_THAN:
    return boundary ? Range.greaterThan(ceil) : Range.greaterThan(decrement(ceil, timeUnit));
  case GREATER_THAN_OR_EQUAL:
    return Range.greaterThan(decrement(ceil, timeUnit));
  default:
    throw Util.unexpected(comparison);
  }
}
 
Example 3
Source File: DateUtilsBasic.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 获取从 start 到 end 的时间范围内每间隔 pitch 分钟的时间字符串集合. 
 * 如 getTimeList("2011-05-04 13:00:00", "2011-05-04 13:30:00", 5, "yyyy-MM-dd hh:mm:ss"),
 * 则返回的 List 中存放的元素为:2011-05-04 01:00:00, 2011-05-04 01:05:00, 2011-05-04 01:10:00, 
 * 2011-05-04 01:15:00, 2011-05-04 01:20:00, 2011-05-04 01:25:00, 2011-05-04 01:30:00。
 * 注意小时的范围为 01~12
 * @param start
 *            开始时间
 * @param end
 *            结束时间
 * @param pitch
 *            分钟间隔
 * @param format
 *            时间格式
 * @return List&lt;String&gt;
 * 			  从 start 到 end 的时间范围内每间隔 pitch 分钟的时间字符串集合.如果 start 与 end 所表示的时间相同,则 List 中只有 start 一个元素
 * 				如果解析过程中出现异常,则 List 中无元素,size=0;
 */
public static List<String> getTimeList(String start, String end, int pitch, String format) {
	List<String> result = new ArrayList<String>();
	SimpleDateFormat formatter = new SimpleDateFormat(format);
	try {
		Date startDate = formatter.parse(start);
		Date endDate = formatter.parse(end);
		Calendar startCalendar = Calendar.getInstance();
		Calendar endCalendar = Calendar.getInstance();
		startCalendar.setTime(startDate);
		endCalendar.setTime(endDate);

		while (startCalendar.before(endCalendar)) {
			result.add(formatter.format(startCalendar.getTime()));
			startCalendar.add(Calendar.MINUTE, pitch);
		}
		if (startCalendar.equals(endCalendar)) {
			result.add(formatter.format(startCalendar.getTime()));
		}
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return result;
}
 
Example 4
Source File: DateRangeRules.java    From Quicksql with MIT License 6 votes vote down vote up
private Range<Calendar> ceilRange(TimeUnitRange timeUnit, SqlKind comparison,
    Calendar c) {
  final Calendar ceil = ceil(c, timeUnit);
  boolean boundary = ceil.equals(c);
  switch (comparison) {
  case EQUALS:
    return Range.openClosed(boundary ? decrement(ceil, timeUnit) : ceil, ceil);
  case LESS_THAN:
    return Range.atMost(decrement(ceil, timeUnit));
  case LESS_THAN_OR_EQUAL:
    return boundary ? Range.atMost(ceil) : Range.atMost(decrement(ceil, timeUnit));
  case GREATER_THAN:
    return boundary ? Range.greaterThan(ceil) : Range.greaterThan(decrement(ceil, timeUnit));
  case GREATER_THAN_OR_EQUAL:
    return Range.greaterThan(decrement(ceil, timeUnit));
  default:
    throw Util.unexpected(comparison);
  }
}
 
Example 5
Source File: FindComparisons.java    From constellation with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether a given <code>Calendar</code> occurred between the
 * two <code>Calendar</code>s provided
 *
 * @param item The value returned for a particular GraphElement.
 * @param comparisonA The query value.
 * @param comparisonB The second query value.
 * @return <code>true</code> if the <code>Calendar</code> occurred
 * between the two comparisons, <code>false</code> if it did not.
 * @see Calendar
 */
public static boolean evaluateBetween(final Calendar item, final Calendar comparisonA, final Calendar comparisonB) {
    if (item != null) {
        final Calendar lower;
        final Calendar upper;

        if (comparisonA.before(comparisonB)) {
            lower = comparisonA;
            upper = comparisonB;
        } else {
            lower = comparisonB;
            upper = comparisonA;
        }

        boolean result = false;
        result = item.equals(lower) || item.equals(upper);
        result |= item.after(lower) && item.before(upper);

        return result;
    } else {
        return false;
    }
}
 
Example 6
Source File: CalendarPeriodCountCalculator.java    From objectlabkit with Apache License 2.0 6 votes vote down vote up
private int calculateConv360EIsda(final Calendar start, final Calendar end) {
    if (start.equals(end)) {
        return 0;
    }
    int diff;
    int dayStart = start.get(Calendar.DAY_OF_MONTH);
    int dayEnd = end.get(Calendar.DAY_OF_MONTH);
    if (start.getActualMaximum(Calendar.DAY_OF_MONTH) == dayStart) {
        dayStart = CalculatorConstants.MONTH_30_DAYS;
    }
    if (end.get(Calendar.MONTH) != Calendar.FEBRUARY && end.getActualMaximum(Calendar.DAY_OF_MONTH) == dayEnd) {
        dayEnd = CalculatorConstants.MONTH_30_DAYS;
    }

    diff = (end.get(Calendar.YEAR) - start.get(Calendar.YEAR)) * CalculatorConstants.YEAR_360 + (end.get(Calendar.MONTH) - start.get(Calendar.MONTH)) * CalculatorConstants.MONTH_30_DAYS
            + dayEnd - dayStart;
    return diff;
}
 
Example 7
Source File: DateUtilsBasic.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 获取从 start 到 end 的时间范围内每间隔 pitch 分钟的时间字符串集合. 
 * 如 getTimeList("2011-05-04 13:00:00", "2011-05-04 13:30:00", 5, "yyyy-MM-dd hh:mm:ss"),
 * 则返回的 List 中存放的元素为:2011-05-04 01:00:00, 2011-05-04 01:05:00, 2011-05-04 01:10:00, 
 * 2011-05-04 01:15:00, 2011-05-04 01:20:00, 2011-05-04 01:25:00, 2011-05-04 01:30:00。
 * 注意小时的范围为 01~12
 * @param start
 *            开始时间
 * @param end
 *            结束时间
 * @param pitch
 *            分钟间隔
 * @param format
 *            时间格式
 * @return List&lt;String&gt;
 * 			  从 start 到 end 的时间范围内每间隔 pitch 分钟的时间字符串集合.如果 start 与 end 所表示的时间相同,则 List 中只有 start 一个元素
 * 				如果解析过程中出现异常,则 List 中无元素,size=0;
 */
public static List<String> getTimeList(String start, String end, int pitch, String format) {
	List<String> result = new ArrayList<String>();
	SimpleDateFormat formatter = new SimpleDateFormat(format);
	try {
		Date startDate = formatter.parse(start);
		Date endDate = formatter.parse(end);
		Calendar startCalendar = Calendar.getInstance();
		Calendar endCalendar = Calendar.getInstance();
		startCalendar.setTime(startDate);
		endCalendar.setTime(endDate);

		while (startCalendar.before(endCalendar)) {
			result.add(formatter.format(startCalendar.getTime()));
			startCalendar.add(Calendar.MINUTE, pitch);
		}
		if (startCalendar.equals(endCalendar)) {
			result.add(formatter.format(startCalendar.getTime()));
		}
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return result;
}
 
Example 8
Source File: ReminderDatePicker.java    From ReminderDatePicker with Apache License 2.0 5 votes vote down vote up
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // An item has been selected in one of our child spinners, so get the selected Date and call the listeners
    if(listener != null) {
        // catch selecting same date twice
        Calendar date = getSelectedDate();
        if(date != null && !date.equals(lastSelectedDate)) {
            listener.onDateSelected(date);
            lastSelectedDate = date;
        }
    }
}
 
Example 9
Source File: WeeklyReportFragment.java    From privacy-friendly-interval-timer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return is the day which is currently shown today?
 */
private boolean isTodayShown() {
    if(day == null){
        return false;
    }
    Calendar start = (Calendar) day.clone();
    start.set(Calendar.DAY_OF_WEEK, day.getFirstDayOfWeek());
    start.set(Calendar.MILLISECOND, 0);
    start.set(Calendar.SECOND, 0);
    start.set(Calendar.MINUTE, 0);
    start.set(Calendar.HOUR_OF_DAY, 0);
    Calendar end = (Calendar) start.clone();
    end.add(Calendar.WEEK_OF_YEAR, 1);
    return (start.before(day) || start.equals(day)) && end.after(day);
}
 
Example 10
Source File: ClientPreparedStatement.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected final long getTimeZoneOffset(long timeInMillis, Calendar cal) {
  Calendar targetCalendar = Calendar.getInstance(cal.getTimeZone());
  targetCalendar.clear();
  targetCalendar.setTimeInMillis(timeInMillis);
  cal.equals(targetCalendar);
  if (this.defaultCalendar == null) {
    this.defaultCalendar = Calendar.getInstance();
  }
  this.defaultCalendar.clear();
  this.defaultCalendar.setTimeInMillis(timeInMillis);
  return targetCalendar.get(Calendar.ZONE_OFFSET)
      - this.defaultCalendar.get(Calendar.ZONE_OFFSET)
      + targetCalendar.get(Calendar.DST_OFFSET)
      - this.defaultCalendar.get(Calendar.DST_OFFSET);
}
 
Example 11
Source File: DurationHelper.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
private Calendar getDateAfterRepeat(Calendar date) {
	Calendar current = TimeZoneUtil.convertToTimeZone(start, date.getTimeZone());
	
	if (repeatWithNoBounds) {
		
    while(current.before(date) || current.equals(date)) { // As long as current date is not past the engine date, we keep looping
    	Calendar newTime = add(current, period);
      if (newTime.equals(current) || newTime.before(current)) {
      	break;
      }
      current = newTime;
    }
    
		
	} else {
		
   int maxLoops = times;
   if (maxIterations > 0) {
     maxLoops = maxIterations - times;
   }
   for (int i = 0; i < maxLoops+1 && !current.after(date); i++) {
     current = add(current, period);
   }
	
	}
	return current.before(date) ? date : TimeZoneUtil.convertToTimeZone(current, clockReader.getCurrentTimeZone());
	
}
 
Example 12
Source File: PerDiemServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Determines if:
 * <ul>
 * <li>A current mileage rate for the KFS-TEM / Document / PER_DIEM_MILEAGE_RATE_EXPENSE_TYPE_CODE is available; if it is not, then per diem cannot be created
 * </ul>
 * @param form the form with the document on it, which may help in making such a decision
 */
@Override
public boolean isMileageRateAvailableForAllPerDiem(TravelDocument doc) {
    final String defaultPerDiemMileageRate = getDefaultPerDiemMileageRateExpenseType();
    if (StringUtils.isBlank(defaultPerDiemMileageRate)) {
        return false;
    }
    if (StringUtils.isBlank(doc.getTripTypeCode()) || doc.getTripBegin() == null || doc.getTripEnd() == null) {
        return true; // we can't create per diem when trip begin or end are blank anyhow - but we shouldn't get the error
    }
    // now we need to loop through each day from begin date to end date to see if there is a validate mileage rate record for it
    Calendar currDay = Calendar.getInstance();
    currDay.setTime(KfsDateUtils.clearTimeFields(doc.getTripBegin()));
    Calendar lastDay = Calendar.getInstance();
    lastDay.setTime(KfsDateUtils.clearTimeFields(doc.getTripEnd()));

    while (currDay.before(lastDay) || currDay.equals(lastDay)) {
        java.sql.Date effectiveDay = doc.getEffectiveDateForPerDiem(new java.sql.Timestamp(currDay.getTimeInMillis()));
        final MileageRate currDayMileageRate = getMileageRateService().findMileageRateByExpenseTypeCodeAndDate(defaultPerDiemMileageRate, effectiveDay);
        if (currDayMileageRate == null) {
            return false;
        }
        currDay.add(Calendar.DATE, 1);
    }
    // we're good
    return true;
}
 
Example 13
Source File: DateSpinner.java    From ReminderDatePicker with Apache License 2.0 5 votes vote down vote up
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(dateListener != null) {
        // catch selecting same date twice
        Calendar date = getSelectedDate();
        if(date != null && !date.equals(lastSelectedDate)) {
            dateListener.onDateSelected(date);
            lastSelectedDate = date;
        }
    }
}
 
Example 14
Source File: Tools.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
public static Date getScheduledTime() {

        Calendar startTime = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        startTime.set(Calendar.HOUR_OF_DAY, 0);
        startTime.set(Calendar.MINUTE, 0);
        startTime.set(Calendar.SECOND, 0);
        startTime.set(Calendar.MILLISECOND, 0);

        if (startTime.before(now) || startTime.equals(now)) {
            startTime.add(Calendar.DATE, 1);
        }

        return startTime.getTime();
    }
 
Example 15
Source File: CalendarRange.java    From org.openntf.domino with Apache License 2.0 4 votes vote down vote up
@Override
public boolean contains(final Calendar calendar) {
	return (null == calendar) ? false : (calendar.equals(this.first()) || calendar.equals(this.last()));
}
 
Example 16
Source File: TravelDocumentServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Integer calculatePerDiemPercentageFromTimestamp(PerDiemExpense perDiemExpense, Timestamp tripEnd) {
    if (perDiemExpense.getMileageDate() != null) {
        try {
            Collection<String> quarterTimes = parameterService.getParameterValuesAsString(TemParameterConstants.TEM_DOCUMENT.class, TravelParameters.QUARTER_DAY_TIME_TABLE);

            // Take date and compare to the quadrant specified.
            Calendar prorateDate = new GregorianCalendar();
            prorateDate.setTime(perDiemExpense.getMileageDate());

            int quadrantIndex = 4;
            for (String qT : quarterTimes) {
                String[] indexTime = qT.split("=");
                String[] hourMinute = indexTime[1].split(":");

                Calendar qtCal = new GregorianCalendar();
                qtCal.setTime(perDiemExpense.getMileageDate());
                qtCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourMinute[0]));
                qtCal.set(Calendar.MINUTE, Integer.parseInt(hourMinute[1]));

                if (prorateDate.equals(qtCal) || prorateDate.before(qtCal)) {
                    quadrantIndex = Integer.parseInt(indexTime[0]);
                    break;
                }
            }

            // Prorate on trip begin. (12:01 AM arrival = 100%, 11:59 PM arrival = 25%)
            if (tripEnd != null && !KfsDateUtils.isSameDay(prorateDate.getTime(), tripEnd)) {
                return 100 - ((quadrantIndex - 1) * TemConstants.QUADRANT_PERCENT_VALUE);
            }
            else { // Prorate on trip end. (12:01 AM departure = 25%, 11:59 PM arrival = 100%).
                return quadrantIndex * TemConstants.QUADRANT_PERCENT_VALUE;
            }
        }
        catch (IllegalArgumentException e2) {
            LOG.error("IllegalArgumentException.", e2);
        }
    }

    return 100;
}
 
Example 17
Source File: BaseCourseOfferingImport.java    From unitime with Apache License 2.0 4 votes vote down vote up
private boolean elementMeetings(Element element, Class_ c) throws Exception {
	String elementName = "meeting";
	boolean changed = false;
	Vector<Meeting> meetings = new Vector<Meeting>();
       if(element.element(elementName) != null){
		Calendar sessionStartDate = Calendar.getInstance();
		sessionStartDate.setTime(session.getSessionBeginDateTime());
		
		Calendar sessionClassesEndDate = Calendar.getInstance();
		sessionClassesEndDate.setTime(session.getExamBeginDate());				
		sessionClassesEndDate.add(Calendar.DAY_OF_MONTH, -1);
		
		Calendar sessionEndDate = Calendar.getInstance();
		sessionEndDate.setTime(session.getSessionEndDateTime());
		
		for (Iterator<?> it = element.elementIterator(elementName); it.hasNext();){
			Element meetingElement = (Element) it.next();
			String startDateStr = getOptionalStringAttribute(meetingElement, "startDate");
			String endDateStr = getOptionalStringAttribute(meetingElement, "endDate");
			String startTime = getRequiredStringAttribute(meetingElement, "startTime", elementName);
			String endTime = getRequiredStringAttribute(meetingElement, "endTime", elementName);
			String days = getRequiredStringAttribute(meetingElement, "days", elementName);
			String building = getOptionalStringAttribute(meetingElement, "building");
			String roomNbr = getOptionalStringAttribute(meetingElement, "room");
			String location = getOptionalStringAttribute(meetingElement, "location");
			Calendar startDate = null;
			Calendar endDate = null;
			if (startDateStr == null && endDateStr == null){
				startDate = sessionStartDate;
				endDate = sessionClassesEndDate;			
			} else if (dateFormat != null) {
				startDate = Calendar.getInstance();
				startDate.setTime(CalendarUtils.getDate(startDateStr, dateFormat));
				endDate = Calendar.getInstance();
				endDate.setTime(CalendarUtils.getDate(endDateStr, dateFormat));
			} else {
				startDate = getCalendarForDate(startDateStr);
				endDate = getCalendarForDate(endDateStr);
			}
			if(endDate.before(startDate)){
				endDate.add(Calendar.YEAR, 1);
			}
			
			if (endDate.equals(sessionEndDate) || (endDate.before(sessionEndDate) && endDate.after(sessionClassesEndDate))){
				if(startDate.before(sessionClassesEndDate)){
					endDate = sessionClassesEndDate;
				}
			}
			
			TimeObject timeObject = new TimeObject(startTime, endTime, days);

			Vector<Room> rooms = new Vector<Room>();
			Vector<NonUniversityLocation> nonUniversityLocations = new Vector <NonUniversityLocation>();

			if (building != null && roomNbr != null){
				Room r = findRoom(null, building, roomNbr);
				if (r != null) {
					rooms.add(r);
				} else {
					addMissingLocation(building + " " + roomNbr + " - " + c.getSchedulingSubpart().getControllingCourseOffering().getSubjectArea().getSubjectAreaAbbreviation());
				}
			} else if (location != null){
				NonUniversityLocation nul = findNonUniversityLocation(null, location, c.getManagingDept());
				if (nul != null) {
					nonUniversityLocations.add(nul);
				} else {
					addMissingLocation(location + " - " + c.getSchedulingSubpart().getControllingCourseOffering().getSubjectArea().getSubjectAreaAbbreviation());
				}
			}
			
			Vector<Calendar> startDates = new Vector<Calendar>();
			startDates.add(startDate);
			
			Vector<Calendar> endDates = new Vector<Calendar>();
			endDates.add(endDate);
							
			Vector<Meeting> m = null;
			if (startDate.equals(sessionStartDate) && (endDate.equals(sessionClassesEndDate) || endDate.equals(sessionEndDate))){
				m = getMeetings(session.getDefaultDatePattern(), timeObject, rooms, nonUniversityLocations);	
			} else {
				m = getMeetings(
						startDate.getTime(), 
						endDate.getTime(), 
						createPatternString(startDates, endDates), 
						timeObject, rooms, nonUniversityLocations);
			}
			if(m != null && !m.isEmpty()){
				meetings.addAll(m);
			}
       	}
       	changed = addUpdateClassEvent(c, meetings, null, null);
       	if (changed)
       		c.setDatePattern(assignmentHelper.getDatePattern(c.getEvent()));
       }
       
       return(changed);
}
 
Example 18
Source File: CalendarRegression.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test whether Calendar can be serialized/deserialized correctly
 * even if invalid/customized TimeZone is used.
 */
public void Test4413980() {
    TimeZone savedTimeZone = TimeZone.getDefault();
    try {
        boolean pass = true;
        String[] IDs = new String[]{"Undefined", "PST", "US/Pacific",
            "GMT+3:00", "GMT-01:30"};
        for (int i = 0; i < IDs.length; i++) {
            TimeZone tz = TimeZone.getTimeZone(IDs[i]);
            TimeZone.setDefault(tz);

            Calendar c = Calendar.getInstance();

            // serialize
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream s = new ObjectOutputStream(out);
            s.writeObject(c);
            s.flush();

            // deserialize
            ObjectInputStream t = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));

            if (!c.equals(t.readObject())) {
                pass = false;
                logln("Calendar instance which uses TimeZone <"
                        + IDs[i] + "> is incorrectly serialized/deserialized.");
            } else {
                logln("Calendar instance which uses TimeZone <"
                        + IDs[i] + "> is correctly serialized/deserialized.");
            }
        }
        if (!pass) {
            errln("Fail: Calendar serialization/equality bug");
        }
    } catch (IOException | ClassNotFoundException e) {
        errln("Fail: " + e);
        e.printStackTrace();
    } finally {
        TimeZone.setDefault(savedTimeZone);
    }
}
 
Example 19
Source File: DateRangeRules.java    From calcite with Apache License 2.0 4 votes vote down vote up
private Calendar ceil(Calendar c, TimeUnitRange timeUnit) {
  Calendar floor = floor(c, timeUnit);
  return floor.equals(c) ? floor : increment(floor, timeUnit);
}
 
Example 20
Source File: FindComparisons.java    From constellation with Apache License 2.0 2 votes vote down vote up
/**
 * Determines whether a given <code>Calendar</code> matches the
 * <code>Calendar</code> returned for a given element on the active
 * graph.
 *
 * @param item The value returned for a particular GraphElement.
 * @param comparison The query value.
 * @return <code>true</code> if the <code>Calendar</code> matches,
 * <code>false</code> if it does not.
 * @see Calendar
 */
public static boolean evaluateOccurredOn(final Calendar item, final Calendar comparison) {
    return item != null && comparison != null && item.equals(comparison);
}