Java Code Examples for java.util.Date.compareTo()

The following are Jave code examples for showing how to use compareTo() of the java.util.Date 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: org.xtext.dsl.restaurante   File: RestauranteValidator.java   View Source Code Vote up 6 votes
@Check
public void checkFecha(final Restaurante restaurante) {
  try {
    SimpleDateFormat formateadorFecha = new SimpleDateFormat("dd-MM-yyyy");
    Date fechaDada = formateadorFecha.parse(restaurante.getFecha());
    Calendar fechaActual = Calendar.getInstance();
    Date _time = fechaActual.getTime();
    boolean _greaterThan = (fechaDada.compareTo(_time) > 0);
    if (_greaterThan) {
      this.error("La fecha tiene que ser igual o menor que la actual", 
        RestaurantePackage.Literals.RESTAURANTE__FECHA, RestauranteValidator.FECHA_INVALIDA);
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 2
Project: teasy   File: DateUtils.java   View Source Code Vote up 5 votes
public static int compareDatesString(String dateString, String anotherDateString, SimpleDateFormat simpleDateFormat) {
    final Date date;
    final Date anotherDate;
    try {
        date = simpleDateFormat.parse(dateString);
        anotherDate = simpleDateFormat.parse(anotherDateString);
    } catch (ParseException e) {
        throw new AssertionError("Incorrect date format" + e);
    }
    return date.compareTo(anotherDate);
}
 
Example 3
Project: ctsms   File: UserPermissionProfileBean.java   View Source Code Vote up 5 votes
@Override
public String getModifiedAnnotation() {
	if (userPermissionProfilesOut != null && userPermissionProfilesOut.size() > 0) {
		Long version = null;
		UserOutVO modifiedUser = null;
		Date modifiedTimestamp = null;
		Iterator<UserPermissionProfileOutVO> it = userPermissionProfilesOut.iterator();
		while (it.hasNext()) {
			UserPermissionProfileOutVO userPermissionProfilesOutVO = it.next();
			Date tagValueModifiedTimestamp = userPermissionProfilesOutVO.getModifiedTimestamp();
			if (modifiedTimestamp == null || (tagValueModifiedTimestamp != null && modifiedTimestamp.compareTo(tagValueModifiedTimestamp) < 0)) {
				modifiedUser = userPermissionProfilesOutVO.getModifiedUser();
				modifiedTimestamp = tagValueModifiedTimestamp;
			}
			if (version == null) {
				version = userPermissionProfilesOutVO.getVersion();
			} else {
				version = Math.max(version.longValue(), userPermissionProfilesOutVO.getVersion());
			}
		}
		if (version == null || modifiedUser == null || modifiedTimestamp == null) {
			return super.getModifiedAnnotation();
		} else {
			return WebUtil.getModifiedAnnotation(version.longValue(), modifiedUser, modifiedTimestamp);
		}
	} else {
		return super.getModifiedAnnotation();
	}
}
 
Example 4
Project: calendar-component   File: CalendarItem.java   View Source Code Vote up 5 votes
/**
 * Get the amount of minutes for the event on a specific day. This is useful
 * if the event spans several days.
 *
 * @param targetDay
 *            The date to check
 * @return the amount of minutes for the event on a specific day. This is useful
 * if the event spans several days.
 */
public long getRangeInMinutesForDay(Date targetDay) {

    long rangeInMinutesForDay;

    // we must take into account that here can be not only 1 and 2 days, but
    // 1, 2, 3, 4... days first and last days - special cases all another
    // days between first and last - have range "ALL DAY"
    if (isTimeOnDifferentDays()) {
        if (targetDay.compareTo(getStart()) == 0) { // for first day
            rangeInMinutesForDay = DateConstants.DAYINMINUTES
                    - (getStartTime().getTime() - getStart().getTime())
                    / DateConstants.MINUTEINMILLIS;

        } else if (targetDay.compareTo(getEnd()) == 0) { // for last day
            rangeInMinutesForDay = (getEndTime().getTime()
                    - getEnd().getTime())
                    / DateConstants.MINUTEINMILLIS;

        } else { // for in-between days
            rangeInMinutesForDay = DateConstants.DAYINMINUTES;
        }
    } else { // simple case - period is in one day
        rangeInMinutesForDay = getRangeInMinutes();
    }
    return rangeInMinutesForDay;
}
 
Example 5
Project: neoscada   File: ChangeEntryComparator.java   View Source Code Vote up 5 votes
@Override
public int compare ( final ChangeEntry o1, final ChangeEntry o2 )
{
    final Date d1 = o1.getDate ();
    final Date d2 = o2.getDate ();
    if ( !this.invert )
    {
        return d1.compareTo ( d2 );
    }
    else
    {
        return -d1.compareTo ( d2 );
    }
}
 
Example 6
Project: ctsms   File: WebUtil.java   View Source Code Vote up 5 votes
private static Boolean getExpired(Date today, Date expiration) {
	if (today != null && expiration != null) {
		if (today.compareTo(expiration) > 0) {
			return true;
		} else {
			return false;
		}
	}
	return null;
}
 
Example 7
Project: aem-epic-tool   File: DataUtil.java   View Source Code Vote up 5 votes
public static int compareDates(Object o1, Object o2) {
    Date d1 = DataUtil.parseDate(String.valueOf(o1));
    Date d2 = DataUtil.parseDate(String.valueOf(o2));
    if (d1 == null && d2 == null) {
        return 0;
    } else if (d1 == null) {
        return 1;
    } else if (d2 == null) {
        return -1;
    } else {
        return d2.compareTo(d1);
    }
}
 
Example 8
Project: remittanceparse   File: Transactions.java   View Source Code Vote up 5 votes
public Transactions(
        File inputJsonFile, Date minimumDate, Date maximumDate) throws IOException {
    JSONArray jsonArray = new JSONArray(
            FileUtils.readFileToString(inputJsonFile, StandardCharsets.UTF_8));

    for (int i = 0; i < jsonArray.length(); i++) {
        Transaction transaction = new Transaction(jsonArray.getJSONObject(i));
        final Date saleDate = transaction.getSaleDate();
        if (saleDate.compareTo(minimumDate) >= 0 && saleDate.compareTo(maximumDate) <= 0)
            transactions.add(transaction);
    }
}
 
Example 9
Project: EasyTodo   File: TodoEvent.java   View Source Code Vote up 5 votes
public boolean isEventExpired(){
    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    Date date = c.getTime();
    return date.compareTo(eventDeadline) > 0;
}
 
Example 10
Project: AssistantBySDK   File: RemindPresenter.java   View Source Code Vote up 5 votes
/**
 * 获取当天提醒第一条记录索引
 **/
@Override
public int getTodayFirstPosition() {
    for (int i = 0; i < showDatas.size(); i++) {
        Date rdate = showDatas.get(i).t.getRdate();
        if (rdate.compareTo(TimeUtils.getTodayDate()) >= 0
                && rdate.before(TimeUtils.getTomorrow())) {
            return i + 1;
        }
    }
    return -1;
}
 
Example 11
Project: ctsms   File: CvPositionPDFVOComparator.java   View Source Code Vote up 5 votes
@Override
public int compare(CvPositionPDFVO a, CvPositionPDFVO b) {
	if (a != null && b != null) {
		CvSectionVO cvSectionA = a.getSection();
		CvSectionVO cvSectionB = b.getSection();
		if (cvSectionA != null && cvSectionB != null) {
			if (cvSectionA.getPosition() < cvSectionB.getPosition()) {
				return -1;
			} else if (cvSectionA.getPosition() > cvSectionB.getPosition()) {
				return 1;
			} else {
				Date dateA = (a.getStart() != null ? a.getStart() : a.getStop());
				Date dateB = (b.getStart() != null ? b.getStart() : b.getStop());
				if (dateA != null && dateB != null) {
					return dateA.compareTo(dateB);
				} else if (dateA == null && dateB != null) {
					return -1;
				} else if (dateA != null && dateB == null) {
					return 1;
				} else {
					return 0;
				}
			}
		} else if (cvSectionA == null && cvSectionB != null) {
			return -1;
		} else if (cvSectionA != null && cvSectionB == null) {
			return 1;
		} else {
			return 0;
		}
	} else if (a == null && b != null) {
		return -1;
	} else if (a != null && b == null) {
		return 1;
	} else {
		return 0;
	}
}
 
Example 12
Project: unitimes   File: MakeAssignmentsForClassEvents.java   View Source Code Vote up 4 votes
protected int getWeek(Date date) {
    for (int idx=0;idx+1<iWeekDate.size();idx++)
        if (date.compareTo(iWeekDate.elementAt(idx))<0) return idx;
    return iWeekDate.size()-1;
}
 
Example 13
Project: convertigo-engine   File: TemporalInputStream.java   View Source Code Vote up 4 votes
private long findPosition(File file, Date date) throws IOException {
	RandomAccessFile raf = new RandomAccessFile(file, "r");
	
	try {
		Date cur_date = extractDate(raf);
		if (cur_date != null) {
			int compare = date.compareTo(cur_date);
			if (compare > 0) {
				date.setTime(date.getTime() - 1);
				long min = raf.getFilePointer();
				long max = raf.length();
				Date last_date = null;
				long last_pos = 0;
				while (cur_date != null && !cur_date.equals(last_date) && !cur_date.equals(date)) {
					last_date = cur_date;
					last_pos = raf.getFilePointer();
					long cur = min + ((max - min) / 2);
					raf.seek(cur);
					cur_date = extractDate(raf);
					if (cur_date == null || date.compareTo(cur_date) < 0) {
						max = cur;
					} else {
						min = cur;
					}
				}
				date.setTime(date.getTime() + 1);
				
				if (cur_date != null && date.compareTo(cur_date) < 0) {
					raf.seek(min);
					cur_date = extractDate(raf);
				}
				
				// Fix #1788 : 'Out of range Date' exception when start date is 2011-01-25 12:32 for log file of #1787
				// can find next cur_date but last_date is a valid candidate for the end date
				if (cur_date == null && last_date != null) {
					cur_date = last_date;
					raf.seek(last_pos);
				}
				while (cur_date != null && date.compareTo(cur_date) > 0) {
					raf.skipBytes(1);
					cur_date = extractDate(raf);
				}
			}
			if (cur_date != null) {
				return raf.getFilePointer();
			}
		}
		throw new IOException("Out of range Date");
	} finally {
		raf.close();
	}
}
 
Example 14
Project: iBase4J   File: Assert.java   View Source Code Vote up 4 votes
/** 未来某一天 */
public static void future(Date date, String key) {
	if (date != null && date.compareTo(new Date()) <= 0) {
		throw new IllegalArgumentException(getMessage(key + "_NOT_FUTURE"));
	}
}
 
Example 15
Project: rapidminer   File: Tools.java   View Source Code Vote up 4 votes
/** Returns true if the date d1 is greater than date d1 or both are equal */
public static boolean isGreaterEqual(Date d1, Date d2) {
	return isEqual(d1, d2) || d1 != null && d1.compareTo(d2) > 0;
}
 
Example 16
Project: Spring-Boot-Server   File: AppCustomerRestful.java   View Source Code Vote up 4 votes
/**
 *
 * @Description: 查询任务
 * @param
 * @return  List<PageData>
 * @throws Exception
 * @Data: 2017/3/2 下午4:47
 *
 */
@RequestMapping(value = "/customerTitles")
public PageData customerTitles(@RequestBody PageData pd){
	String handlerId=pd.getString("HANDLER_ID");
	if(StringUtils.isNotBlank(handlerId)){

		Calendar queryTime = Calendar.getInstance();
		queryTime.setTime(new Date());
		queryTime.add(Calendar.SECOND,titleIdTimeOut*-1);


		//查询所有未结束的消息
		Criteria criteria = new Criteria();
		criteria.andOperator(Criteria.where("HANDLER_ID").is(handlerId),Criteria.where("STATUS").is("1"),Criteria.where("CHANGE_TIME").gte(queryTime.getTime()));
		Query query = new Query(criteria);
		List<PageData> allTitle=mongoTemplate.find(query,PageData.class,"IM_TITLE");

		String handlerRedis=String.join("_",customerCounter,"HANDLER",handlerId);
		if(!redisTemplate.hasKey(handlerRedis)){
			return WebResult.requestFailed(401,"本客服以及下线!",null);
		}
		//客服人员上次更新时间
		Date updateDate=(Date) redisTemplate.opsForValue().get(handlerRedis);
		Date now=new Date();

		List<PageData> newTitle=new ArrayList<>();
		List<PageData> oldTitle=new ArrayList<>();
		for(PageData title:allTitle){
			String titleId=title.getString("TITLE_ID");
			if(redisTemplate.hasKey(String.join("_",customerCounter,titleId))){
				//查询新消息
				PageData contentPd=new PageData();
				contentPd.put("TITLE_ID",titleId);
				contentPd.put("STARTTIME",updateDate);
				contentPd.put("ENDTIME",now);
				contentPd.put("TITLE_TYPE","1");
				List<PageData> contentList=loopContent(contentPd);
				title.put("CONTENTLIST",contentList);

				//区分新旧回话
				Date changeTime=(Date)title.get("CHANGE_TIME");
				if(changeTime.compareTo(updateDate)>0){
					newTitle.add(title);
				}else{
					oldTitle.add(title);
				}
			}else{
				//关闭回话
				Criteria updCriteria = new Criteria();
				updCriteria.orOperator(Criteria.where("TITLE_ID").is(pd.get("TITLE_ID")));
				mongoTemplate.updateFirst(new Query(updCriteria), Update.update("STATUS","0"),"IM_TITLE");
			}
		}
		PageData retPd=new PageData();
		retPd.put("NEWTITLE",newTitle);
		retPd.put("OLDTITLE",oldTitle);
		retPd.put("IMGSERVER",imageServerUrl);

		//更新客服时间
		pd.put("_id",false);
		pd.put("_id",handlerId);
		pd.put("CHANGE_TIME",new Date());
		pd.put("CHANGE_UID",pd.getString("HANDLER_ID"));
		mongoTemplate.save(pd,"IM_INCUSTOMER");
		redisTemplate.opsForValue().set(handlerRedis, now, handlerTimeOut, TimeUnit.SECONDS);
		return WebResult.requestSuccess(retPd);
	}else{
		return WebResult.requestFailed(504,"参数错误",null);
	}
}
 
Example 17
Project: NotiCap   File: NotificationListenerService.java   View Source Code Vote up 4 votes
private static boolean isTimeBetween(String fromTime, String toTime, String nowTime) throws ParseException {
	String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9])$";
	if (fromTime.matches(reg) && toTime.matches(reg) && nowTime.matches(reg)) {
		boolean valid;

		Date startTime = new SimpleDateFormat("HH:mm", Locale.US).parse(fromTime);
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setTime(startTime);

		Date currentTime = new SimpleDateFormat("HH:mm", Locale.US).parse(nowTime);
		Calendar currentCalendar = Calendar.getInstance();
		currentCalendar.setTime(currentTime);

		Date endTime = new SimpleDateFormat("HH:mm", Locale.US).parse(toTime);
		Calendar endCalendar = Calendar.getInstance();
		endCalendar.setTime(endTime);

		if (currentTime.compareTo(endTime) < 0) {
			currentCalendar.add(Calendar.DATE, 1);
			currentTime = currentCalendar.getTime();
		}

		if (startTime.compareTo(endTime) < 0) {
			startCalendar.add(Calendar.DATE, 1);
			startTime = startCalendar.getTime();
		}

		if (currentTime.before(startTime)) {
			valid = false;
		} else {
			if (currentTime.after(endTime)) {
				endCalendar.add(Calendar.DATE, 1);
				endTime = endCalendar.getTime();
			}

			valid = currentTime.before(endTime);
		}
		return valid;
	} else {
		throw new IllegalArgumentException("Not a valid time, expecting HH:mm format");
	}
}
 
Example 18
Project: automat   File: Assert.java   View Source Code Vote up 4 votes
/** 未来某一天 */
public static void future(Date date, String key) {
	if (date != null && date.compareTo(new Date()) <= 0) {
		throw new IllegalArgumentException(getMessage(key + "_NOT_FUTURE"));
	}
}
 
Example 19
Project: grooves   File: Database.java   View Source Code Vote up 4 votes
public static boolean isTimestampInRange(
        Date lowerBoundExclusive, Date timestamp, Date upperBoundInclusive) {
    return (lowerBoundExclusive == null || timestamp.compareTo(lowerBoundExclusive) > 0)
            && timestamp.compareTo(upperBoundInclusive) <= 0;
}
 
Example 20
Project: lams   File: DateUtils.java   View Source Code Vote up 2 votes
/**
 * Determines how two dates compare up to no more than the specified 
 * most significant field.
 * 
 * @param date1 the first date, not <code>null</code>
 * @param date2 the second date, not <code>null</code>
 * @param field the field from <code>Calendar</code>
 * @return a negative integer, zero, or a positive integer as the first 
 * date 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 2.6
 */
public static int truncatedCompareTo(Date date1, Date date2, int field) {
    Date truncatedDate1 = truncate(date1, field);
    Date truncatedDate2 = truncate(date2, field);
    return truncatedDate1.compareTo(truncatedDate2);
}