下面列出了java.util.Date#compareTo ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unused")
private static boolean compare(String one, String sybmol, String two) throws ParseException {
boolean result = false;
Date date1 = yyyyMmDd.parse(one);
Date date2 = yyyyMmDd.parse(two);
if (">".equals(sybmol)) {
result = date1.compareTo(date2) > 0;
} else if ("<".equals(sybmol)) {
result = date1.compareTo(date2) < 0;
} else if ("=".equals(sybmol) || "==".equals(sybmol)) {
result = date1.compareTo(date2) == 0;
} else if (">=".equals(sybmol)) {
result = date1.compareTo(date2) >= 0;
} else if ("<=".equals(sybmol)) {
result = date1.compareTo(date2) <= 0;
}
return result;
}
public boolean contains(Date date) {
if ((date.compareTo(mStartDate) >= 0)
&& (date.compareTo(mDueDate) <= 0)) {
return true;
}
return false;
}
public int compare(Topic topic, Topic otherTopic)
{
if (topic != null && otherTopic != null
&& topic instanceof Topic && otherTopic instanceof Topic)
{
// title1 = ((Topic) topic).getTitle();
// title2 = ((Topic) otherTopic).getTitle();
//
// index1 = Integer.valueOf(lookupOrderList.indexOf(title1));
// index2 = Integer.valueOf(lookupOrderList.indexOf(title2));
//
// /** expecting elements to exist in lookupOrderedList */
// return index1.compareTo(index2);
if(lookupOrderList.indexOf(((Topic) topic).getTitle()) >= 0 && lookupOrderList.indexOf(((Topic) otherTopic).getTitle()) < 0)
{
return -1;
}
if(lookupOrderList.indexOf(((Topic) topic).getTitle()) < 0 && lookupOrderList.indexOf(((Topic) otherTopic).getTitle()) >= 0)
{
return 1;
}
Date date1=((Topic) topic).getCreated();
Date date2=((Topic) otherTopic).getCreated();
return date1.compareTo(date2);
}
return -1;
}
/**
* Singer can restart itself if # of failures exceeds threshold, and in daily
* cadence. The following is singer restart related configuration:
*
* singer.restart.onFailures=true singer.restart.numberOfFailuresAllowed=100
* singer.restart.daily=true singer.restart.dailyRestartUtcTimeRangeBegin=02:30
* singer.restart.dailyRestartUtcTimeRangeEnd=03:30
*/
private static SingerRestartConfig parseSingerRestartConfig(PropertiesConfiguration configHeader) throws ConfigurationException {
SingerRestartConfig restartConfig = new SingerRestartConfig();
AbstractConfiguration subsetConfig = new SubsetConfiguration(configHeader,
SingerConfigDef.SINGER_RESTART_PREFIX);
if (subsetConfig.containsKey(SingerConfigDef.ON_FAILURES)) {
restartConfig.restartOnFailures = subsetConfig.getBoolean(SingerConfigDef.ON_FAILURES);
}
if (subsetConfig.containsKey(SingerConfigDef.NUMBER_OF_FAILURES_ALLOWED)) {
restartConfig.numOfFailuesAllowed = subsetConfig
.getInt(SingerConfigDef.NUMBER_OF_FAILURES_ALLOWED);
}
if (subsetConfig.containsKey(SingerConfigDef.DAILY_RESTART_FLAG)) {
restartConfig.restartDaily = subsetConfig.getBoolean(SingerConfigDef.DAILY_RESTART_FLAG);
}
if (restartConfig.restartDaily) {
if (!subsetConfig.containsKey(SingerConfigDef.DAILY_RESTART_TIME_BEGIN)
|| !subsetConfig.containsKey(SingerConfigDef.DAILY_RESTART_TIME_END)) {
throw new ConfigurationException("Daily restart time range is not set correctly");
}
restartConfig.dailyRestartUtcTimeRangeBegin = subsetConfig
.getString(SingerConfigDef.DAILY_RESTART_TIME_BEGIN);
restartConfig.dailyRestartUtcTimeRangeEnd = subsetConfig
.getString(SingerConfigDef.DAILY_RESTART_TIME_END);
Date startTime = SingerUtils.convertToDate(restartConfig.dailyRestartUtcTimeRangeBegin);
Date endTime = SingerUtils.convertToDate(restartConfig.dailyRestartUtcTimeRangeEnd);
if (endTime.compareTo(startTime) <= 0) {
throw new ConfigurationException("Daily restart end time is not later than start time");
}
}
return restartConfig;
}
@Override
public int compare(AdminUser user1, AdminUser user2) {
Date date1 = user1.getVisited();
Date date2 = user2.getVisited();
if (date1 == null && date2 == null) {
return 0;
} else if (date1 == null) {
return 1;
} else if (date2 == null) {
return -1;
} else {
return date1.compareTo(date2);
}
}
/**
* 比较时间大小
* @param first
* @param second
* @return 返回0 first等于second, 返回-1 first小于second,, 返回1 first大于second
*/
public static int compareToDate(Date first, Date second) {
int result = first.compareTo(second);
if (result < 0) {
return -1;
} else if (result > 0) {
return 1;
}
return 0;
}
/**
* start - public method to start Web Socket For Streaming Quote
* @param apiKey
* @param userId
* @param publicToken
*/
public void start(String apiKey, String userId, String publicToken){
if(ZStreamingConfig.isStreamingQuoteStartAtBootup()){
//start Streaming Quote WebSocket - immediately
System.out.println("ZStreamingQuoteControl.start(): Starting Streaming Quote WS");
startStreamingQuote(apiKey, userId, publicToken);
} else{
//start Streaming Quote WebSocket - at market open
Thread t = new Thread(new Runnable(){
private boolean runnable = true;
private DateFormat dtFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private TimeZone timeZone = TimeZone.getTimeZone("IST");
private String refTime = todaysDate + " " + QUOTE_STREAMING_TIME;
@Override
public void run() {
dtFmt.setTimeZone(timeZone);
try {
Date timeRef = dtFmt.parse(refTime);
while(runnable){
Date timeNow = Calendar.getInstance(timeZone).getTime();
if(timeNow.compareTo(timeRef) >= 0){
System.out.println("ZStreamingQuoteControl.start().StreamingQuoteStartThread.run(): Starting Streaming Quote WS at: " + timeNow);
runnable = false;
startStreamingQuote(apiKey, userId, publicToken);
}
Thread.sleep(1000);
}
} catch (ParseException e1) {
System.out.println("ZStreamingQuoteControl.start(): ParseException while parsing time: [" + refTime + "], cause: " + e1.getMessage());
} catch (InterruptedException e) {
System.out.println("ZStreamingQuoteControl.start(): InterruptedException for Thread sleep");
}
}
});
t.start();
}
}
public static boolean isNewRule(Date val, String deadLine) throws ParseException {
Date start = new SimpleDateFormat("yyyy-MM-dd").parse(deadLine);
if (val.compareTo(start) >= 0) {
return true;
} else {
return false;
}
}
public static boolean isDateToday(long milliSeconds) {
Calendar toCheck = Calendar.getInstance();
toCheck.setTimeInMillis(milliSeconds);
Date toCheckDate = toCheck.getTime();
toCheck.setTimeInMillis(System.currentTimeMillis());
toCheck.set(Calendar.HOUR_OF_DAY, 0);
toCheck.set(Calendar.MINUTE, 0);
toCheck.set(Calendar.SECOND, 0);
Date startDate = toCheck.getTime();
return toCheckDate.compareTo(startDate) > 0;
}
/**
* Checks if the permission is currently active by checking the start and
* end dates.
* @return true if the permission is active; otherwise false.
*/
public boolean isActive() {
Date now = new Date();
return now.compareTo(startDate) >= 0 &&
(endDate == null || now.compareTo(endDate) <= 0);
}
protected int compare(Date n1, Date n2) {
return (n1 == null ? n2 == null ? 0 : -1 : n2 == null ? 1 : n1.compareTo(n2));
}
public static int compareDateWithNow(Date date1) {
Date date2 = new Date();
int rnum = date1.compareTo(date2);
return rnum;
}
public int compare(Object item, Object anotherItem){
Date date1 = ((DecoratedCompiledStatisticsByTopic) item).getTopicDate();
Date date2 = ((DecoratedCompiledStatisticsByTopic) anotherItem).getTopicDate();
return date1.compareTo(date2);
}
/**
* Validate that business object data is supported by the business object data destroy feature.
*
* @param businessObjectDataEntity the business object data entity
* @param businessObjectDataKey the business object data key
*/
void validateBusinessObjectData(BusinessObjectDataEntity businessObjectDataEntity, BusinessObjectDataKey businessObjectDataKey)
{
// Get business object format for this business object data.
BusinessObjectFormatEntity businessObjectFormatEntity = businessObjectDataEntity.getBusinessObjectFormat();
// Create a version-less key for the business object format.
BusinessObjectFormatKey businessObjectFormatKey =
new BusinessObjectFormatKey(businessObjectDataKey.getNamespace(), businessObjectDataKey.getBusinessObjectDefinitionName(),
businessObjectDataKey.getBusinessObjectFormatUsage(), businessObjectDataKey.getBusinessObjectFormatFileType(), null);
// Get the latest version of the format to retrieve retention information.
BusinessObjectFormatEntity latestVersionBusinessObjectFormatEntity = businessObjectFormatEntity.getLatestVersion() ? businessObjectFormatEntity :
businessObjectFormatDao.getBusinessObjectFormatByAltKey(businessObjectFormatKey);
// Get retention information.
String retentionType =
latestVersionBusinessObjectFormatEntity.getRetentionType() != null ? latestVersionBusinessObjectFormatEntity.getRetentionType().getCode() : null;
Integer retentionPeriodInDays = latestVersionBusinessObjectFormatEntity.getRetentionPeriodInDays();
// Get the current timestamp from the database.
Timestamp currentTimestamp = herdDao.getCurrentTimestamp();
// Validate that retention information is specified for this business object format.
if (retentionType != null)
{
switch (retentionType)
{
case RetentionTypeEntity.PARTITION_VALUE:
Assert.notNull(retentionPeriodInDays,
String.format("Retention period in days must be specified for %s retention type.", RetentionTypeEntity.PARTITION_VALUE));
Assert.isTrue(retentionPeriodInDays > 0,
String.format("A positive retention period in days must be specified for %s retention type.", RetentionTypeEntity.PARTITION_VALUE));
// Try to convert business object data primary partition value to a timestamp.
// If conversion is not successful, the method returns a null value.
Date primaryPartitionValue = businessObjectDataHelper.getDateFromString(businessObjectDataEntity.getPartitionValue());
// If primary partition values is not a date, this business object data is not supported by the business object data destroy feature.
if (primaryPartitionValue == null)
{
throw new IllegalArgumentException(String
.format("Primary partition value \"%s\" cannot get converted to a valid date. Business object data: {%s}",
businessObjectDataEntity.getPartitionValue(), businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey)));
}
// Compute the relative primary partition value threshold date based on the current timestamp and retention period value.
Date primaryPartitionValueThreshold = new Date(HerdDateUtils.addDays(currentTimestamp, -retentionPeriodInDays).getTime());
// Validate that this business object data has it's primary partition value before or equal to the threshold date.
if (primaryPartitionValue.compareTo(primaryPartitionValueThreshold) > 0)
{
throw new IllegalArgumentException(String.format(
"Business object data fails retention threshold check for retention type \"%s\" with retention period of %d days. " +
"Business object data: {%s}", retentionType, retentionPeriodInDays,
businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey)));
}
break;
case RetentionTypeEntity.BDATA_RETENTION_DATE:
// Retention period in days value must only be specified for PARTITION_VALUE retention type.
Assert.isNull(retentionPeriodInDays, String.format("A retention period in days cannot be specified for %s retention type.", retentionType));
// Validate that the retention information is specified for business object data with retention type as BDATA_RETENTION_DATE.
Assert.notNull(businessObjectDataEntity.getRetentionExpiration(), String
.format("Retention information with retention type %s must be specified for the Business Object Data: {%s}", retentionType,
businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey)));
// Validate that the business object data retention expiration date is in the past.
if (!(businessObjectDataEntity.getRetentionExpiration().before(currentTimestamp)))
{
throw new IllegalArgumentException(String.format(
"Business object data fails retention threshold check for retention type \"%s\" with retention expiration date %s. " +
"Business object data: {%s}", retentionType, businessObjectDataEntity.getRetentionExpiration(),
businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey)));
}
break;
default:
throw new IllegalArgumentException(String
.format("Retention type \"%s\" is not supported by the business object data destroy feature. Business object format: {%s}",
retentionType, businessObjectFormatHelper.businessObjectFormatKeyToString(businessObjectFormatKey)));
}
}
else
{
throw new IllegalArgumentException(String
.format("Retention information is not configured for the business object format. Business object format: {%s}",
businessObjectFormatHelper.businessObjectFormatKeyToString(businessObjectFormatKey)));
}
}
private Action[] getActionsBetween(Date start, Date end) {
List<Action> actions = new ArrayList<>();
List<String> ids = new ArrayList<>();
for (String actionKey : actionKeys) {
String id = getActionID(actionKey);
if (!ids.contains(id)) {
Date actionStartDate;
Date actionEndDate;
try {
actionStartDate = getActionStartDate(actionKey);
actionEndDate = getActionEndDate(actionKey);
} catch (ParseException pe) {
Logger.getLogger(CalendarConnector.class.getName()).
log(Level.SEVERE, "Failed to parse action date");
continue;
}
// Case 0: action inside event timeframe
// Action should start AFTER or AT THE SAME TIME as the event,
// and
// Action should end BEFORE or AT THE SAME TIME as the event
boolean test0 = actionStartDate.compareTo(start) >= 0
&& actionEndDate.compareTo(end) <= 0;
// Case 1: action intersects start of timeframe
// Action end time must be between start and end of event
boolean test1 = actionEndDate.compareTo(start) > 0
&& actionEndDate.compareTo(end) <= 0;
// Case 2: action intersects end of timeframe
// Action start time must be between start and end of event
boolean test2 = actionStartDate.compareTo(start) >= 0
&& actionStartDate.compareTo(end) < 0;
// Case 3: event inside action timeframe
// Action should start AND END before the event is complete
boolean test3 = start.compareTo(actionStartDate) >= 0
&& end.compareTo(actionEndDate) <= 0;
if (test0 || test1 || test2 || test3) {
VCalendarAction a = new VCalendarAction(this, rpc, actionKey);
a.setCaption(getActionCaption(actionKey));
a.setIconUrl(getActionIcon(actionKey));
a.setActionStartDate(start);
a.setActionEndDate(end);
actions.add(a);
ids.add(id);
}
}
}
return actions.toArray(new Action[actions.size()]);
}
public int compare(Object item, Object anotherItem){
Date date1 = ((DecoratedCompiledStatisticsByTopic) item).getTopicDate();
Date date2 = ((DecoratedCompiledStatisticsByTopic) anotherItem).getTopicDate();
return date2.compareTo(date1);
}
@Override
public int compare(VisitScheduleItemOutVO a, VisitScheduleItemOutVO b) {
if (a != null && b != null) {
if (!temporalOnly) {
TrialOutVO trialA = a.getTrial();
TrialOutVO trialB = b.getTrial();
if (trialA != null && trialB != null) {
int trialComparison = comp(trialA.getName(), trialB.getName());
if (trialComparison != 0) {
return trialComparison;
}
} else if (trialA == null && trialB != null) {
return -1;
} else if (trialA != null && trialB == null) {
return 1;
}
ProbandGroupOutVO groupA = a.getGroup();
ProbandGroupOutVO groupB = b.getGroup();
if (groupA != null && groupB != null) {
int groupComparison = comp(groupA.getToken(), groupB.getToken());
if (groupComparison != 0) {
return groupComparison;
}
} else if (groupA == null && groupB != null) {
return -1;
} else if (groupA != null && groupB == null) {
return 1;
}
VisitOutVO visitA = a.getVisit();
VisitOutVO visitB = b.getVisit();
if (visitA != null && visitB != null) {
int visitComparison = comp(visitA.getToken(), visitB.getToken());
if (visitComparison != 0) {
return visitComparison;
}
} else if (visitA == null && visitB != null) {
return -1;
} else if (visitA != null && visitB == null) {
return 1;
}
String tokenA = a.getToken();
String tokenB = b.getToken();
if (tokenA != null && tokenB != null) {
int tokenComparison = comp(tokenA, tokenB);
if (tokenComparison != 0) {
return tokenComparison;
}
} else if (tokenA == null && tokenB != null) {
return -1;
} else if (tokenA != null && tokenB == null) {
return 1;
}
}
Date startA = a.getStart();
Date startB = b.getStart();
if (startA != null && startB != null) {
int startComparison = startA.compareTo(startB);
if (startComparison != 0) {
return startComparison;
}
} else if (startA == null && startB != null) {
return -1;
} else if (startA != null && startB == null) {
return 1;
}
if (a.getId() > b.getId()) {
return 1;
} else if (a.getId() < b.getId()) {
return -1;
} else {
return 0;
}
} else if (a == null && b != null) {
return -1;
} else if (a != null && b == null) {
return 1;
} else {
return 0;
}
}
/**
* 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 3.0
*/
public static int truncatedCompareTo(Date date1, Date date2, int field) {
Date truncatedDate1 = truncate(date1, field);
Date truncatedDate2 = truncate(date2, field);
return truncatedDate1.compareTo(truncatedDate2);
}
/**
* 两个时间比较
*
* @param date
* @return
*/
public static int compareDateWithNow(Date date1) {
Date date2 = new Date();
int rnum = date1.compareTo(date2);
return rnum;
}
/**
* 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 3.0
*/
public static int truncatedCompareTo(Date date1, Date date2, int field) {
Date truncatedDate1 = truncate(date1, field);
Date truncatedDate2 = truncate(date2, field);
return truncatedDate1.compareTo(truncatedDate2);
}