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

The following are Jave code examples for showing how to use equals() 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: SonoESEO-Android   File: CalendarFragment.java   View Source Code Vote up 6 votes
/**
 * This function will return a list of dates which are between the start and end dates given.
 *
 * @param start : The start date.
 * @param end   : The end date.
 * @return The list of dates.
 */
private List<Date> getDatesBetween(Date start, Date end) {
    Date cursor = start;

    Calendar cal = Calendar.getInstance();
    List<Date> results = new ArrayList<>();
    while (!cursor.equals(end)) {
        results.add(cursor);

        cal.setTime(cursor);
        cal.add(Calendar.DATE, 1);
        cursor = cal.getTime();
    }
    if (!results.contains(end)) {
        results.add(end);
    }
    return results;
}
 
Example 2
Project: CharmMylynConnector   File: CharmRepositoryConnector.java   View Source Code Vote up 6 votes
@Override
public boolean hasTaskChanged(@NonNull TaskRepository taskRepository, @NonNull ITask task,
		@NonNull TaskData taskData) {

	Date changedAtTaskData = taskData.getAttributeMapper()
			.getDateValue(taskData.getRoot().getAttribute(TaskAttribute.DATE_MODIFICATION));
	Date changedAtTask = task.getModificationDate();

	if (changedAtTask == null || changedAtTaskData == null)
		return true;

	if (!changedAtTask.equals(changedAtTaskData))
		return true;

	return false;
}
 
Example 3
Project: openjdk-jdk10   File: CalendarRegression.java   View Source Code Vote up 6 votes
/**
 * Adding 12 months behaves differently from adding 1 year
 */
public void Test4165343() {
    GregorianCalendar calendar = new GregorianCalendar(1996, FEBRUARY, 29);
    Date start = calendar.getTime();
    logln("init date: " + start);
    calendar.add(MONTH, 12);
    Date date1 = calendar.getTime();
    logln("after adding 12 months: " + date1);
    calendar.setTime(start);
    calendar.add(YEAR, 1);
    Date date2 = calendar.getTime();
    logln("after adding one year : " + date2);
    if (date1.equals(date2)) {
        logln("Test passed");
    } else {
        errln("Test failed");
    }
}
 
Example 4
Project: Hybrid-Cloud-Applications-and-Services   File: DatabaseAccess.java   View Source Code Vote up 5 votes
public static Weather getAirportWeather(String date, String airportTo, String username, String password) {
	//enable basic login
	HttpHelper.setAuth(username,password);
	HttpHelper.enableAuth(true);
	JsonNode response = HttpHelper.connect("https://twcservice.mybluemix.net/api/weather/v3/location/point?iataCode="+ airportTo +"&language=en-US", "GET", null);
	if (response == null) {
		return null;
	}
	//query the data and get its lat and lon
	String city = response.path("location").path("city").asText();
	double lat = response.path("location").path("latitude").asDouble();
	String latitude = Double.toString(lat);
	double lon = response.path("location").path("longitude").asDouble();
	String longitude = Double.toString(lon);
	JsonNode response2 = HttpHelper.connect("https://twcservice.mybluemix.net/api/weather/v1/geocode/" + latitude + "/" + longitude + "/forecast/daily/10day.json", "GET", null);
	HttpHelper.enableAuth(false);
	JsonNode d10 = response2.get("forecasts");
	try{
		//query data and reformat it to match the Weather class
		DateFormat dates = new SimpleDateFormat("yyyy-MM-dd");
		Date future = dates.parse(date);
		for (JsonNode day : d10) {
			String[] days = day.path("fcst_valid_local").asText().split("T");
			Date dayDate = dates.parse(days[0]);
       		if(future.equals(dayDate)){
       			String weath = day.path("day").path("phrase_22char").asText();
       			int temperture = day.path("day").path("temp").asInt();
       			String narrative = day.path("day").path("narrative").asText();
       			Weather weather = new Weather(date, city, weath, temperture, narrative);
				return weather;
       		}
   		}		
	} catch (Exception e) {
		e.printStackTrace();
	}
	//If we can't find the matching day, return null
	return null;
}
 
Example 5
Project: lams   File: CronExpression.java   View Source Code Vote up 5 votes
/**
 * Indicates whether the given date satisfies the cron expression. Note that
 * milliseconds are ignored, so two Dates falling on different milliseconds
 * of the same second will always have the same result here.
 * 
 * @param date the date to evaluate
 * @return a boolean indicating whether the given date satisfies the cron
 *         expression
 */
public boolean isSatisfiedBy(Date date) {
    Calendar testDateCal = Calendar.getInstance(getTimeZone());
    testDateCal.setTime(date);
    testDateCal.set(Calendar.MILLISECOND, 0);
    Date originalDate = testDateCal.getTime();
    
    testDateCal.add(Calendar.SECOND, -1);
    
    Date timeAfter = getTimeAfter(testDateCal.getTime());

    return ((timeAfter != null) && (timeAfter.equals(originalDate)));
}
 
Example 6
Project: rapidminer   File: Equals.java   View Source Code Vote up 5 votes
@Override
protected Boolean compute(Date left, Date right) {
	if (left == null && right == null) {
		return true;
	}
	if (left == null || right == null) {
		return false;
	}
	return left.equals(right);
}
 
Example 7
Project: lams   File: RAMJobStore.java   View Source Code Vote up 5 votes
protected boolean applyMisfire(TriggerWrapper tw) {

        long misfireTime = System.currentTimeMillis();
        if (getMisfireThreshold() > 0) {
            misfireTime -= getMisfireThreshold();
        }

        Date tnft = tw.trigger.getNextFireTime();
        if (tnft == null || tnft.getTime() > misfireTime 
                || tw.trigger.getMisfireInstruction() == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY) { 
            return false; 
        }

        Calendar cal = null;
        if (tw.trigger.getCalendarName() != null) {
            cal = retrieveCalendar(tw.trigger.getCalendarName());
        }

        signaler.notifyTriggerListenersMisfired((OperableTrigger)tw.trigger.clone());

        tw.trigger.updateAfterMisfire(cal);

        if (tw.trigger.getNextFireTime() == null) {
            tw.state = TriggerWrapper.STATE_COMPLETE;
            signaler.notifySchedulerListenersFinalized(tw.trigger);
            synchronized (lock) {
                timeTriggers.remove(tw);
            }
        } else if (tnft.equals(tw.trigger.getNextFireTime())) {
            return false;
        }

        return true;
    }
 
Example 8
Project: JRediClients   File: CronExpression.java   View Source Code Vote up 5 votes
/**
 * Indicates whether the given date satisfies the cron expression. Note that
 * milliseconds are ignored, so two Dates falling on different milliseconds
 * of the same second will always have the same result here.
 * 
 * @param date the date to evaluate
 * @return a boolean indicating whether the given date satisfies the cron
 *         expression
 */
public boolean isSatisfiedBy(Date date) {
    Calendar testDateCal = Calendar.getInstance(getTimeZone());
    testDateCal.setTime(date);
    testDateCal.set(Calendar.MILLISECOND, 0);
    Date originalDate = testDateCal.getTime();
    
    testDateCal.add(Calendar.SECOND, -1);
    
    Date timeAfter = getTimeAfter(testDateCal.getTime());

    return ((timeAfter != null) && (timeAfter.equals(originalDate)));
}
 
Example 9
Project: ibm-cos-sdk-java   File: JodaTime.java   View Source Code Vote up 5 votes
private static boolean checkParseRfc822Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat(
            "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    Date expected = sdf.parse(formatted);
    Date actual2 = new Date(DateUtils.rfc822DateFormat.parseMillis(formatted));
    return expected.equals(actual2);
}
 
Example 10
Project: jdk8u-jdk   File: TimeParsing.java   View Source Code Vote up 5 votes
private static  void checkGeneralized(Date d0, byte[] b, String text) throws Exception {
  Date d1 = decodeGeneralized(b);
  if( !d0.equals(d1) ) {
    throw new Exception("GeneralizedTime " + text + " failed: " + d1.toGMTString());
  } else {
    System.out.println("GeneralizedTime " + text + " ok");
  }
}
 
Example 11
Project: Android-SQLite-Master-Project   File: ComparatorUtils.java   View Source Code Vote up 5 votes
@SuppressWarnings("SimplifiableIfStatement")
public static boolean compareDateNullSafety(@Nullable Date first, @Nullable Date second) {
    if (first == null)
        return second == null;
    else if (second == null)
        return false;
    else
        return first.equals(second);
}
 
Example 12
Project: pgsqlblocks   File: DBBlocksJournalProcess.java   View Source Code Vote up 5 votes
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof DBBlocksJournalProcess)) return false;

    DBBlocksJournalProcess other = (DBBlocksJournalProcess) o;

    Date xactStart = process.getQuery().getXactStart();
    Date otherXactStart = other.getProcess().getQuery().getXactStart();

    boolean isSameXactStart = xactStart == null ? otherXactStart == null : xactStart.equals(otherXactStart);
    boolean isSamePid = process.getPid() == other.getProcess().getPid();

    return isSameXactStart && isSamePid && childrenEquals(process.getChildren(), other.getProcess().getChildren());
}
 
Example 13
Project: ibm-cos-sdk-java   File: JodaTime.java   View Source Code Vote up 5 votes
private static boolean checkParseIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    String alternative = DateUtils.iso8601DateFormat.print(date.getTime());
    if (formatted.equals(alternative)) {
        Date expectedDate = sdf.parse(formatted);
        Date actualDate = DateUtils.doParseISO8601Date(formatted);
        return expectedDate.equals(actualDate);
    }
    return false;
}
 
Example 14
Project: qfii-tracker   File: ConnectParser.java   View Source Code Vote up 5 votes
protected void parseRangeAndUpdate(Date startDate, Date endDate, String directory,
    PostgreStorage storage, String market)
    throws IOException, ParseException {
  while (startDate.before(endDate) || startDate.equals(endDate)) {
    parseAndUpdate(startDate, directory, storage, market);
    startDate = DateUtils.addDays(startDate, 1);
  }
}
 
Example 15
Project: AtomMatrikel   File: Downloader.java   View Source Code Vote up 4 votes
public void read() throws Exception {
    FTPClient ftpClient = new FTPClient();
    ftpClient.setBufferSize(1024 * 1024);
    ftpClient.setDefaultTimeout(1000);
    ftpClient.setControlEncoding("UTF-8");
    ftpClient.setDataTimeout(10000);
    ZipFile zipFile = new ZipFile();
    Parser parser = new Parser();
    URL feedUrl = new URL("https://download.kortforsyningen.dk/sites/default/files/feeds/MATRIKELKORT_GML.xml");
    SyndFeedInput input = new SyndFeedInput();
    System.out.println("Henter Atom feed....\n");

    SyndFeed feed = input.build(new XmlReader(feedUrl));
    System.out.println("Feed Titel: " + feed.getTitle());
    Date lastPublishedDate;
    Date currentDate;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String fileName;
    Integer elavsKode;

    Track track = new Track();
    String lastStr = track.getLastFromDb();
    lastPublishedDate = sdf.parse(lastStr);

    System.out.println("\nSidste entry: " + lastStr + "\n");

    this.login(ftpClient);

    for (SyndEntry entry : (List<SyndEntry>) feed.getEntries()) {

        System.out.println("\n--------------\n");

        currentDate = entry.getPublishedDate();

        if (currentDate.before(lastPublishedDate) || currentDate.equals(lastPublishedDate)) {
            break;
        }

        System.out.println("Published Date: " + entry.getPublishedDate() + "\n");

        // Get the Links
        for (SyndLinkImpl link : (List<SyndLinkImpl>) entry.getLinks()) {
            System.out.println("Link: " + link.getHref());
            fileName = link.getHref().split("/")[7];
            elavsKode = Integer.valueOf(fileName.split("_")[0]);
            track.storeInDb(currentDate.toString(), elavsKode);

            // Get the file
            this.c(ftpClient, fileName, zipFile);

            // Get xml stream from zip-file
            ZipInputStream zin = zipFile.getGml(fileName);

            // Parse the xml and insert in database
            parser.build(zin, elavsKode);

            // Delete the file
            File file = new File(fileName);
            file.delete();
        }


    }
    // logout the user, returned true if logout successfully
    ftpClient.disconnect();
    System.out.println("Alt hentet...");
    System.out.println("FTP forbindelse afbrydes.");


}
 
Example 16
Project: BachelorPraktikum   File: VaultDao.java   View Source Code Vote up 4 votes
/**
 * Searches the database for duplicate entries and removes them accordingly.
 *
 * @return True if no duplicate entries were found or all duplicate entries were successfully removed from the database.
 *          False if a duplicate entry could not be removed.
 */
public boolean removeDuplicates() {
    // DELETE FROM MyTable WHERE RowId NOT IN (SELECT MIN(RowId) FROM MyTable GROUP BY Col1, Col2, Col3);
    // but we need a workaround for the or mapper
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .prepare();
        CloseableIterator<VaultEntry> iterator = vaultDao.iterator(query);

        Date startGenerationTimestamp = null;
        List<VaultEntry> tmpList = new ArrayList<>();
        List<Long> duplicateId = new ArrayList<>();
        while (iterator.hasNext()) {
            VaultEntry entry = iterator.next();
            if (startGenerationTimestamp == null) {
                // start up
                startGenerationTimestamp = entry.getTimestamp();
                tmpList.add(entry);
            } else if (!startGenerationTimestamp
                    .equals(entry.getTimestamp())) {
                // not same timestamp --> new line generation
                startGenerationTimestamp = entry.getTimestamp();
                tmpList.clear();
                tmpList.add(entry);
            } else {
                // same timestamp --> check if it is a duplicate
                for (VaultEntry item : tmpList) {
                    if (item.equals(entry)) {
                        // duplicate --> delete and move on
                        duplicateId.add(entry.getId());
                        break;
                    }
                }
            }
        }

        // delete duplicates
        int lines = vaultDao.deleteIds(duplicateId);
        LOG.log(Level.INFO, "Removed {0} duplicates", lines);
    } catch (SQLException exception) {
        LOG.log(Level.SEVERE, "Error while db query", exception);
        return false;
    }

    return true;
}
 
Example 17
Project: alfresco-repository   File: DatePropertyValueComparator.java   View Source Code Vote up 4 votes
/**
 * @see org.alfresco.repo.action.evaluator.compare.PropertyValueComparator#compare(java.io.Serializable, java.io.Serializable, org.alfresco.repo.action.evaluator.compare.ComparePropertyValueOperation)
 */
public boolean compare(Serializable propertyValue, Serializable compareValue, ComparePropertyValueOperation operation)
{
    boolean result = false;
    
    if (operation == null)
    {
        operation = ComparePropertyValueOperation.EQUALS;
    }
    
    Date propertyDate = getDate(propertyValue);
    Date compareDate = getDate(compareValue);
    
    switch (operation)
    {
        case EQUALS:
        {
            result = propertyDate.equals(compareDate);
            break;
        }
        case LESS_THAN:
        {
            result = propertyDate.before(compareDate);
            break;
        }
        case LESS_THAN_EQUAL:
        {
            result = (propertyDate.equals(compareDate) || propertyDate.before(compareDate));
            break;
        }
        case GREATER_THAN:
        {
            result = propertyDate.after(compareDate);
            break;
        }
        case GREATER_THAN_EQUAL:
        {
            result = (propertyDate.equals(compareDate) || propertyDate.after(compareDate));
            break;
        }
        default:
        {
            // Raise an invalid operation exception
            throw new ActionServiceException(
                    MSGID_INVALID_OPERATION, 
                    new Object[]{operation.toString()});
        }            
    }
    
    return result;
}
 
Example 18
Project: DateRangePicker   File: CalendarPickerView.java   View Source Code Vote up 4 votes
static boolean betweenDates(Date date, Calendar minCal, Calendar maxCal) {
  final Date min = minCal.getTime();
  return (date.equals(min) || date.after(min)) // >= minCal
      && date.before(maxCal.getTime()); // && < maxCal
}
 
Example 19
Project: logistimo-web-service   File: MarkerBuilder.java   View Source Code Vote up 4 votes
private MarkerModel buildMarkerFromTransaction(ITransaction trans, Locale locale,
                                                 String timezone) {
    double lat = NumberUtil.getDoubleValue(trans.getLatitude());
    double lng = NumberUtil.getDoubleValue(trans.getLongitude());
    if (lat == 0 && lng == 0) {
      return null;
    }
    String thisTransUid = trans.getSourceUserId();
    Date thisTransTimestamp = trans.getTimestamp();
    if (thisTransUid != null && !thisTransUid.isEmpty() && thisTransUid.equals(transUid)
        && thisTransTimestamp != null && thisTransTimestamp.equals(transTimestamp)) {
      return null;
    }
    transUid = thisTransUid;
    transTimestamp = thisTransTimestamp;
    MarkerModel model = new MarkerModel();
    model.latitude = lat;
    model.longitude = lng;
    model.accuracy = NumberUtil.getDoubleValue(trans.getGeoAccuracy());
//        tid = trans.getKeyString();
    PersistenceManager pm = null;
    try {
      pm = PMF.get().getPersistenceManager();
      IKiosk k = JDOUtils.getObjectById(IKiosk.class, trans.getKioskId(), pm);
      IKiosk lk = null;
      if (trans.getLinkedKioskId() != null) {
        lk = JDOUtils.getObjectById(IKiosk.class, trans.getLinkedKioskId(), pm);
      }
      String transType = trans.getType();
      StringBuilder title = new StringBuilder();

      title.append(TransactionUtil.getDisplayName(transType, locale));
      if (ITransaction.TYPE_ISSUE.equals(transType) || ITransaction.TYPE_TRANSFER
          .equals(transType)) {
        if (lk != null) {
          title.append(" to ").append(lk.getName()).append(", ").append(lk.getCity());
        }
        title.append(" from");
      } else if (ITransaction.TYPE_RECEIPT.equals(transType)) {
        if (lk != null) {
          title.append(" from ").append(lk.getName()).append(", ").append(lk.getCity());
        }
        title.append(" to");
      } else {
        title.append(" at");
      }
      title.append(" ").append(k.getName()).append(", ").append(k.getCity()).append(" on ")
          .append(LocalDateUtil.format(trans.getTimestamp(), locale, timezone));
      model.title = title.toString();
    } catch (Exception e) {
      xLogger.warn("{0} when getting kiosk for ID {1} during trans. geo-data acquisition: {2}",
          e.getClass().getName(), trans.getKioskId(), e.getMessage());
    } finally {
      if (pm != null) {
        pm.close();
      }
    }
    return model;
  }
 
Example 20
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();
	}
}