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

The following examples show how to use java.util.Calendar#compareTo() . 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: SDEFWriter.java    From mpxj with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Write a calendar exception.
 *
 * @param parentCalendar parent calendar instance
 * @param record calendar exception instance
 * @throws IOException
 */
private void writeCalendarException(ProjectCalendar parentCalendar, ProjectCalendarException record) throws IOException
{
   m_buffer.setLength(0);
   Calendar stepDay = DateHelper.popCalendar(record.getFromDate()); // Start at From Date, then step through days...
   Calendar lastDay = DateHelper.popCalendar(record.getToDate()); // last day in this exception

   m_buffer.append("HOLI ");
   m_buffer.append(SDEFmethods.lset(parentCalendar.getUniqueID().toString(), 2));

   while (stepDay.compareTo(lastDay) <= 0)
   {
      m_buffer.append(m_formatter.format(stepDay.getTime()).toUpperCase() + " ");
      stepDay.add(Calendar.DAY_OF_MONTH, 1);
   }
   m_writer.println(m_buffer.toString());

   DateHelper.pushCalendar(stepDay);
   DateHelper.pushCalendar(lastDay);
}
 
Example 2
Source File: DateAndTime.java    From StatsAgg with Apache License 2.0 6 votes vote down vote up
public static int Compare_CurrentTimeVsSpecifiedTime(String hoursAndMinutes) {
    
    if (hoursAndMinutes == null) {
        return COMPARE_ERROR_CODE;
    }
    
    try {
        Calendar todayAtSpecifiedTime = getCalendarWithTodaysDateAtSpecifiedTime(hoursAndMinutes, "HH:mm");

        Calendar currentSystemDateAndTime = Calendar.getInstance();
        int comparisonResult = currentSystemDateAndTime.compareTo(todayAtSpecifiedTime);

        return comparisonResult;
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
        return COMPARE_ERROR_CODE;
    }
}
 
Example 3
Source File: DateUtils.java    From springboot-security-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * 计算两个Date之间的工作日时间差
 *
 * @param start 开始时间
 * @param end   结束时间
 * @return int 返回两天之间的工作日时间
 */
public static int countDutyday(Date start, Date end) {
    if (start == null || end == null) return 0;
    if (start.after(end)) return 0;
    Calendar c_start = Calendar.getInstance();
    Calendar c_end = Calendar.getInstance();
    c_start.setTime(start);
    c_end.setTime(end);
    //时分秒毫秒清零
    c_start.set(Calendar.HOUR_OF_DAY, 0);
    c_start.set(Calendar.MINUTE, 0);
    c_start.set(Calendar.SECOND, 0);
    c_start.set(Calendar.MILLISECOND, 0);
    c_end.set(Calendar.HOUR_OF_DAY, 0);
    c_end.set(Calendar.MINUTE, 0);
    c_end.set(Calendar.SECOND, 0);
    c_end.set(Calendar.MILLISECOND, 0);
    //初始化第二个日期,这里的天数可以随便的设置
    int dutyDay = 0;
    while (c_start.compareTo(c_end) < 0) {
        if (c_start.get(Calendar.DAY_OF_WEEK) != 1 && c_start.get(Calendar.DAY_OF_WEEK) != 7)
            dutyDay++;
        c_start.add(Calendar.DAY_OF_YEAR, 1);
    }
    return dutyDay;
}
 
Example 4
Source File: DateUtil.java    From maven-archetype with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *
 * @param date1
 * @param date2
 * @return
 */
public static boolean isSameDay(Date date1,Date date2){
	if(date1 == null && date2 == null ){
		return true;
	}
	if(date1 == null || date2 == null ){
		return false;
	}
	
	Calendar cal1 = getCalendar(getDate(date1));
	Calendar cal2 = getCalendar(getDate(date2));
	if(cal1 == null && cal2 == null){
		return true;
	}
	if(cal1 != null && cal1.compareTo(cal2) == 0){
		return true;
	}
	return false;
}
 
Example 5
Source File: NightTimeVerifier.java    From QuickLyric with GNU General Public License v3.0 5 votes vote down vote up
public static boolean check(Context context) {
    Calendar currentTime = Calendar.getInstance();

    SharedPreferences pref = context.getSharedPreferences("night_time", Context.MODE_PRIVATE);
    int startHour = pref.getInt("startHour", 42);
    int startMinute = pref.getInt("startMinute", 0);
    int endHour = pref.getInt("endHour", 0);
    int endMinute = pref.getInt("endMinute", 0);

    if (startHour >= 25)
        return false;

    //Start Time
    Calendar startTime = Calendar.getInstance();
    startTime.set(Calendar.HOUR_OF_DAY, startHour);
    startTime.set(Calendar.MINUTE, startMinute);
    //Stop Time
    Calendar stopTime = Calendar.getInstance();
    stopTime.set(Calendar.HOUR_OF_DAY, endHour);
    stopTime.set(Calendar.MINUTE, endMinute);

    if (stopTime.compareTo(startTime) < 0) {
        if (currentTime.compareTo(stopTime) < 0) {
            currentTime.add(Calendar.DATE, 1);
        }
        stopTime.add(Calendar.DATE, 1);
    }
    return currentTime.compareTo(startTime) >= 0 && currentTime.compareTo(stopTime) < 0;
}
 
Example 6
Source File: CalendarTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.util.Calendar#compareTo(Calendar)
 */
public void test_compareToLjava_util_Calendar_null() {
	Calendar cal = Calendar.getInstance();
	try {
		cal.compareTo(null);
		fail("should throw NullPointerException");
	} catch (NullPointerException e) {
		// expected
	}
}
 
Example 7
Source File: RecordWriterManager.java    From datacollector with Apache License 2.0 5 votes vote down vote up
List<String> getGlobs() throws ELEvalException {
  List<String> globs = new ArrayList<>();
  Calendar endCalendar = Calendar.getInstance(timeZone);
  if (pathResolver.getTimeIncrementUnit() > -1) {

    // we need to scan dirs from last batch minus the cutOff time
    Calendar calendar = Calendar.getInstance(timeZone);
    calendar.setTime(new Date(context.getLastBatchTime()));
    calendar.add(Calendar.MILLISECOND, (int) -cutOffMillis);
    // adding an extra hour to scan
    calendar.add(Calendar.HOUR, -1);

    // set the calendar to the floor date of the computed start time
    calendar.setTime(pathResolver.getFloorDate(calendar.getTime()));

    LOG.info("Looking for uncommitted files from '{}' onwards", calendar.getTime());

    // iterate from last batch time until now at the dir template minimum time precision increments
    // we create a glob for each template time tick
    for (; calendar.compareTo(endCalendar) < 0;
         calendar.add(pathResolver.getTimeIncrementUnit(), pathResolver.getTimeIncrementValue())) {
      globs.add(createGlob(calendar));
    }
  } else {
    // in this case we don't use the calendar at all as the dir template does not use time functions
    globs.add(createGlob(endCalendar));
  }
  return globs;
}
 
Example 8
Source File: DateUtils.java    From mumu with Apache License 2.0 5 votes vote down vote up
/**
 * 根据单位字段比较两个时间
 * 
 * @param date
 *            时间1
 * @param otherDate
 *            时间2
 * @param withUnit
 *            单位字段,从Calendar field取值
 * @return 等于返回0值, 大于返回大于0的值 小于返回小于0的值
 */
public static int compareTime(Date date, Date otherDate, int withUnit) {
	Calendar dateCal = Calendar.getInstance();
	dateCal.setTime(date);
	Calendar otherDateCal = Calendar.getInstance();
	otherDateCal.setTime(otherDate);

	dateCal.clear(Calendar.YEAR);
	dateCal.clear(Calendar.MONTH);
	dateCal.set(Calendar.DATE, 1);
	otherDateCal.clear(Calendar.YEAR);
	otherDateCal.clear(Calendar.MONTH);
	otherDateCal.set(Calendar.DATE, 1);
	switch (withUnit) {
	case Calendar.HOUR:
		dateCal.clear(Calendar.MINUTE);
		otherDateCal.clear(Calendar.MINUTE);
	case Calendar.MINUTE:
		dateCal.clear(Calendar.SECOND);
		otherDateCal.clear(Calendar.SECOND);
	case Calendar.SECOND:
		dateCal.clear(Calendar.MILLISECOND);
		otherDateCal.clear(Calendar.MILLISECOND);
	case Calendar.MILLISECOND:
		break;
	default:
		throw new IllegalArgumentException("withUnit 单位字段 " + withUnit + " 不合法!!");
	}
	return dateCal.compareTo(otherDateCal);
}
 
Example 9
Source File: NewYear.java    From 4pdaClient-plus with Apache License 2.0 5 votes vote down vote up
private static boolean checkDate() {
    int year = GregorianCalendar.getInstance().get(Calendar.YEAR);

    Calendar startDate = new GregorianCalendar(year, Calendar.JANUARY, 1);
    Calendar endDate = new GregorianCalendar(year, Calendar.JANUARY, 7);

    Calendar currentDate = GregorianCalendar.getInstance();
    return (startDate.compareTo(currentDate) * currentDate.compareTo(endDate)) >= 0;
}
 
Example 10
Source File: Alarm.java    From android-DirectBoot with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(@NonNull Alarm other) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DATE, date);
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);

    Calendar otherCal = Calendar.getInstance();
    otherCal.set(Calendar.MONTH, other.month);
    otherCal.set(Calendar.DATE, other.date);
    otherCal.set(Calendar.HOUR_OF_DAY, other.hour);
    otherCal.set(Calendar.MINUTE, other.minute);
    return calendar.compareTo(otherCal);
}
 
Example 11
Source File: BookingDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
public Boolean mapRow(final ResultSet rs, int rowNum) throws SQLException {

            int startTimeSeconds = rs.getInt("int_backout_start");
            int stopTimeSeconds = rs.getInt("int_blackout_stop");
            if (stopTimeSeconds <= startTimeSeconds) {
                stopTimeSeconds = stopTimeSeconds + 86400;
            }

            Calendar startTime = Calendar.getInstance();
            startTime.set(Calendar.HOUR_OF_DAY, 0);
            startTime.set(Calendar.MINUTE, 0);
            startTime.set(Calendar.SECOND, 0);
            startTime.add(Calendar.SECOND, startTimeSeconds);

            Calendar stopTime = Calendar.getInstance();
            stopTime.set(Calendar.HOUR_OF_DAY, 0);
            stopTime.set(Calendar.MINUTE, 0);
            stopTime.set(Calendar.SECOND, 0);
            stopTime.add(Calendar.SECOND, stopTimeSeconds);

            Calendar now = Calendar.getInstance();
            if (now.compareTo(startTime) >= 0 && now.compareTo(stopTime) <= 0) {
                return true;
            }

            return false;
        }
 
Example 12
Source File: BookingDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
public Boolean mapRow(final ResultSet rs, int rowNum) throws SQLException {

            int startTimeSeconds = rs.getInt("int_backout_start");
            int stopTimeSeconds = rs.getInt("int_blackout_stop");
            if (stopTimeSeconds <= startTimeSeconds) {
                stopTimeSeconds = stopTimeSeconds + 86400;
            }

            Calendar startTime = Calendar.getInstance();
            startTime.set(Calendar.HOUR_OF_DAY, 0);
            startTime.set(Calendar.MINUTE, 0);
            startTime.set(Calendar.SECOND, 0);
            startTime.add(Calendar.SECOND, startTimeSeconds);

            Calendar stopTime = Calendar.getInstance();
            stopTime.set(Calendar.HOUR_OF_DAY, 0);
            stopTime.set(Calendar.MINUTE, 0);
            stopTime.set(Calendar.SECOND, 0);
            stopTime.add(Calendar.SECOND, stopTimeSeconds);

            Calendar now = Calendar.getInstance();
            if (now.compareTo(startTime) >= 0 && now.compareTo(stopTime) <= 0) {
                return true;
            }

            return false;
        }
 
Example 13
Source File: DateUtils.java    From Lottor with MIT License 5 votes vote down vote up
/**
 * 比较两个日期大小(比较年月日时分秒),com1大于com2返回1,反之返回-1,相等则返回0
 *
 * @param date1
 * @param date2
 * @return
 */
public static int compareDateOfSecond(Date date1, Date date2) {
    Calendar c1 = Calendar.getInstance();
    c1.setTime(date1);
    c1.set(Calendar.MILLISECOND, 0);
    Calendar c2 = Calendar.getInstance();
    c2.setTime(date2);
    c2.set(Calendar.MILLISECOND, 0);
    return c1.compareTo(c2);

}
 
Example 14
Source File: MiBandService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private static final boolean isBetweenValidTime(Date startTime, Date endTime, Date currentTime) {
    //Start Time
    Calendar StartTime = Calendar.getInstance();
    StartTime.setTime(startTime);
    StartTime.set(1, 1, 1);

    Calendar EndTime = Calendar.getInstance();
    EndTime.setTime(endTime);
    EndTime.set(1, 1, 1);

    //Current Time
    Calendar CurrentTime = Calendar.getInstance();
    CurrentTime.setTime(currentTime);
    CurrentTime.set(1, 1, 1);
    if (EndTime.compareTo(StartTime) > 0) {
        if ((CurrentTime.compareTo(StartTime) >= 0) && (CurrentTime.compareTo(EndTime) <= 0)) {
            return true;
        } else {
            return false;
        }
    } else if (EndTime.compareTo(StartTime) < 0) {
        if ((CurrentTime.compareTo(EndTime) >= 0) && (CurrentTime.compareTo(StartTime) <= 0)) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}
 
Example 15
Source File: DateUtils.java    From dbys with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 时间比较(如果myDate>compareDate返回1,<返回-1,相等返回0)
 *
 * @param myDate      时间
 * @param compareDate 要比较的时间
 * @return int
 */
public static int dateCompare(Date myDate, Date compareDate) {
    Calendar myCal = Calendar.getInstance();
    Calendar compareCal = Calendar.getInstance();
    myCal.setTime(myDate);
    compareCal.setTime(compareDate);
    return myCal.compareTo(compareCal);
}
 
Example 16
Source File: Alarm.java    From security-samples with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(@NonNull Alarm other) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DATE, date);
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);

    Calendar otherCal = Calendar.getInstance();
    otherCal.set(Calendar.MONTH, other.month);
    otherCal.set(Calendar.DATE, other.date);
    otherCal.set(Calendar.HOUR_OF_DAY, other.hour);
    otherCal.set(Calendar.MINUTE, other.minute);
    return calendar.compareTo(otherCal);
}
 
Example 17
Source File: RangerValidityScheduleEvaluator.java    From ranger with Apache License 2.0 4 votes vote down vote up
public boolean isApplicable(Calendar now) {
    boolean ret = false;

    RangerPerfTracer perf = null;

    if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
        perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerRecurrenceEvaluator.isApplicable(accessTime=" + now.getTime().getTime() + ")");
    }

    if (recurrence != null && intervalInMinutes > 0) { // recurring schedule

        if (LOG.isDebugEnabled()) {
            LOG.debug("Access-Time:[" + now.getTime() + "]");
        }

        Calendar startOfInterval = getClosestPastEpoch(now);

        if (startOfInterval != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Start-of-Interval:[" + startOfInterval.getTime() + "]");
            }

            Calendar endOfInterval = (Calendar) startOfInterval.clone();
            endOfInterval.add(Calendar.MINUTE, recurrence.getInterval().getMinutes());
            endOfInterval.add(Calendar.HOUR, recurrence.getInterval().getHours());
            endOfInterval.add(Calendar.DAY_OF_MONTH, recurrence.getInterval().getDays());

            endOfInterval.getTime();    // for recomputation
            now.getTime();

            if (LOG.isDebugEnabled()) {
                LOG.debug("End-of-Interval:[" + endOfInterval.getTime() + "]");
            }

            ret = startOfInterval.compareTo(now) <= 0 && endOfInterval.compareTo(now) >= 0;
        }

    } else {
        ret = true;
    }

    RangerPerfTracer.log(perf);
    return ret;
}
 
Example 18
Source File: JcrPackageRegistry.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
public JcrPackage upload(InputStream in, boolean replace)
        throws RepositoryException, IOException, PackageExistsException {

    MemoryArchive archive = new MemoryArchive(true);
    InputStreamPump pump = new InputStreamPump(in , archive);

    // this will cause the input stream to be consumed and the memory archive being initialized.
    Binary bin = session.getValueFactory().createBinary(pump);
    if (pump.getError() != null) {
        Exception error = pump.getError();
        log.error("Error while reading from input stream.", error);
        bin.dispose();
        throw new IOException("Error while reading from input stream", error);
    }

    if (archive.getJcrRoot() == null) {
        String msg = "Stream is not a content package. Missing 'jcr_root'.";
        log.error(msg);
        bin.dispose();
        throw new IOException(msg);
    }

    final MetaInf inf = archive.getMetaInf();
    PackageId pid = inf.getPackageProperties().getId();

    // invalidate pid if path is unknown
    if (pid == null) {
        pid = createRandomPid();
    }
    if (!pid.isValid()) {
        bin.dispose();
        throw new RepositoryException("Unable to create package. Illegal package name.");
    }

    // create parent node
    String path = getInstallationPath(pid) + ".zip";
    String parentPath = Text.getRelativeParent(path, 1);
    String name = Text.getName(path);
    Node parent = mkdir(parentPath, false);

    // remember installation state properties (GRANITE-2018)
    JcrPackageDefinitionImpl.State state = null;
    Calendar oldCreatedDate = null;

    if (parent.hasNode(name)) {
        try (JcrPackage oldPackage = new JcrPackageImpl(this, parent.getNode(name))) {
            JcrPackageDefinitionImpl oldDef = (JcrPackageDefinitionImpl) oldPackage.getDefinition();
            if (oldDef != null) {
                state = oldDef.getState();
                oldCreatedDate = oldDef.getCreated();
            }
        }

        if (replace) {
            parent.getNode(name).remove();
        } else {
            throw new PackageExistsException("Package already exists: " + pid).setId(pid);
        }
    }
    JcrPackage jcrPack = null;
    try {
        jcrPack = createNew(parent, pid, bin, archive);
        JcrPackageDefinitionImpl def = (JcrPackageDefinitionImpl) jcrPack.getDefinition();
        Calendar newCreateDate = def == null ? null : def.getCreated();
        // only transfer the old package state to the new state in case both packages have the same create date
        if (state != null && newCreateDate != null && oldCreatedDate != null && oldCreatedDate.compareTo(newCreateDate) == 0) {
            def.setState(state);
        }
        dispatch(PackageEvent.Type.UPLOAD, pid, null);
        return jcrPack;
    } finally {
        bin.dispose();
        if (jcrPack == null) {
            session.refresh(false);
        } else {
            session.save();
        }
    }
}
 
Example 19
Source File: Lang_21_DateUtils_s.java    From coming with MIT License 2 votes vote down vote up
/**
 * Determines how two calendars compare up to no more than the specified 
 * most significant field.
 * 
 * @param cal1 the first calendar, not <code>null</code>
 * @param cal2 the second calendar, not <code>null</code>
 * @param field the field from <code>Calendar</code>
 * @return a negative integer, zero, or a positive integer as the first 
 * calendar is less than, equal to, or greater than the second.
 * @throws IllegalArgumentException if any argument is <code>null</code>
 * @see #truncate(Calendar, int)
 * @see #truncatedCompareTo(Date, Date, int)
 * @since 3.0
 */
public static int truncatedCompareTo(Calendar cal1, Calendar cal2, int field) {
    Calendar truncatedCal1 = truncate(cal1, field);
    Calendar truncatedCal2 = truncate(cal2, field);
    return truncatedCal1.compareTo(truncatedCal2);
}
 
Example 20
Source File: DateUtils.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Determines how two calendars compare up to no more than the specified 
 * most significant field.
 * 
 * @param cal1 the first calendar, not <code>null</code>
 * @param cal2 the second calendar, not <code>null</code>
 * @param field the field from <code>Calendar</code>
 * @return a negative integer, zero, or a positive integer as the first 
 * calendar is less than, equal to, or greater than the second.
 * @throws IllegalArgumentException if any argument is <code>null</code>
 * @see #truncate(Calendar, int)
 * @see #truncatedCompareTo(Date, Date, int)
 * @since 3.0
 */
public static int truncatedCompareTo(Calendar cal1, Calendar cal2, int field) {
    Calendar truncatedCal1 = truncate(cal1, field);
    Calendar truncatedCal2 = truncate(cal2, field);
    return truncatedCal1.compareTo(truncatedCal2);
}