Java Code Examples for org.joda.time.DateTime#compareTo()

The following examples show how to use org.joda.time.DateTime#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: PhdIndividualProgramProcess.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public boolean isActive(Interval interval) {
    List<Interval> activeStatesIntervals = new ArrayList<Interval>();
    Set<PhdProgramProcessState> states = new TreeSet<PhdProgramProcessState>(new Comparator<PhdProcessState>() {
        @Override
        public int compare(PhdProcessState o1, PhdProcessState o2) {
            DateTime o1StateDate = o1.getStateDate() == null ? o1.getWhenCreated() : o1.getStateDate();
            DateTime o2StateDate = o2.getStateDate() == null ? o2.getWhenCreated() : o2.getStateDate();
            int result = o1StateDate.compareTo(o2StateDate);
            return result != 0 ? result : o1.getExternalId().compareTo(o2.getExternalId());
        }
    });
    states.addAll(getStates());
    DateTime beginActiveDate = null;
    for (PhdProgramProcessState state : states) {
        if (state.getType().isActive() && beginActiveDate == null) {
            beginActiveDate = state.getStateDate() == null ? state.getWhenCreated() : state.getStateDate();
        }
        if ((!state.getType().isActive()) && beginActiveDate != null) {
            activeStatesIntervals.add(new Interval(beginActiveDate,
                    state.getStateDate() == null ? state.getWhenCreated() : state.getStateDate()));
            beginActiveDate = null;
        }
    }
    return activeStatesIntervals.stream().anyMatch(interval::overlaps) || (activeStatesIntervals.isEmpty() && beginActiveDate != null);
}
 
Example 2
Source File: BuyZoneModel.java    From bateman with MIT License 6 votes vote down vote up
@Override
public boolean sell(DateTime time, Session session) {
    if (!session.inMarket(time)) {
        return false;
    }

    BigDecimal open = asset.getTimeSeries().openOnDay(time);
    DateTime buyDate = session.lastTrade().getOpen();
    BigDecimal buyPrice = asset.priceAt(buyDate);
    BigDecimal current = asset.priceAt(time);
    BigDecimal difference = current.subtract(buyPrice);

    // exit if at end of day, if our sell trigger threshold is reached,
    // or if we hit our stop loss

    DateTime endOfDay = asset.getTimeSeries().closeOnDay(time);

    boolean atEndOfDay = time.compareTo(endOfDay) >= 0;

    boolean thresholdReached = difference.compareTo(sellTrigger) >= 0;

    boolean stopLossReached = buyPrice.subtract(current).compareTo(stopLoss) >= 0;

    return atEndOfDay || thresholdReached || stopLossReached;
}
 
Example 3
Source File: Rule.java    From bateman with MIT License 6 votes vote down vote up
private boolean makeSizedTrade(Session session, DateTime time, TradeType type, DateTime end) throws Exception {
    // not going to open a trade on the last day of the session
    if (time.compareTo(end) >= 0) {
        return false;
    }

    int size = moneyManager.sizePosition(account, time);

    /* If we can't buy anything, we can't trade anymore, so stop the session */
    if (size == 0) {
        return false;
    }

    Trade trade = new Trade(asset, time, null, size, type, conditions);
    session.addTrade(trade);
    return true;
}
 
Example 4
Source File: Trade.java    From bateman with MIT License 6 votes vote down vote up
public Trade(Asset asset, DateTime open, DateTime close, int size, TradeType type, Conditions conditions) throws Exception {
    this.asset = asset;
    this.open = open;
    this.close = close;
    this.size = size;
    this.type = type;
    this.conditions = conditions;

    if (!asset.getTimeSeries().hasPriceAt(open) || (isClosed() && !asset.getTimeSeries().hasPriceAt(close))) {
        throw new Exception("Cannot place trades at dates for which no data exists");
    }

    if (isClosed() && (open.compareTo(close) >= 0)) {
        throw new Exception("Open must come before close and existing for a non-zero amount of time");
    }
}
 
Example 5
Source File: DataSegment.java    From druid-api with Apache License 2.0 6 votes vote down vote up
public static Comparator<DataSegment> bucketMonthComparator()
{
  return new Comparator<DataSegment>()
  {
    @Override
    public int compare(DataSegment lhs, DataSegment rhs)
    {
      int retVal;

      DateTime lhsMonth = Granularity.MONTH.truncate(lhs.getInterval().getStart());
      DateTime rhsMonth = Granularity.MONTH.truncate(rhs.getInterval().getStart());

      retVal = lhsMonth.compareTo(rhsMonth);

      if (retVal != 0) {
        return retVal;
      }

      return lhs.compareTo(rhs);
    }
  };
}
 
Example 6
Source File: AcademicServiceRequestSituation.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public int compare(AcademicServiceRequestSituation leftAcademicServiceRequestSituation,
        AcademicServiceRequestSituation rightAcademicServiceRequestSituation) {
    DateTime leftDate = leftAcademicServiceRequestSituation.getSituationDate();
    DateTime rightDate = rightAcademicServiceRequestSituation.getSituationDate();

    if (leftDate == null) {
        leftDate = leftAcademicServiceRequestSituation.getCreationDate();
    }
    if (rightDate == null) {
        rightDate = rightAcademicServiceRequestSituation.getCreationDate();
    }

    int comparationResult = leftDate.compareTo(rightDate);
    return -((comparationResult == 0) ? DomainObjectUtil.COMPARATOR_BY_ID.compare(
            leftAcademicServiceRequestSituation, rightAcademicServiceRequestSituation) : comparationResult);
}
 
Example 7
Source File: AnomalyUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Logs the known anomalies whose window overlaps with the given window, whose range is defined by windowStart
 * and windowEnd.
 *
 * Reason to log the overlapped anomalies: During anomaly detection, the know anomalies are supposedly used to remove
 * abnormal baseline values but not current values. This method provides a check before sending the known anomalies to
 * anomaly detection functions.
 *
 * @param windowStart the inclusive start time of the window
 * @param windowEnd the exclusive end time of the window
 * @param knownAnomalies the known anomalies
 */
public static void logAnomaliesOverlapWithWindow(DateTime windowStart, DateTime windowEnd,
    List<MergedAnomalyResultDTO> knownAnomalies) {
  if (CollectionUtils.isEmpty(knownAnomalies) || windowEnd.compareTo(windowStart) <= 0) {
    return;
  }

  List<MergedAnomalyResultDTO> overlappedAnomalies = new ArrayList<>();
  for (MergedAnomalyResultDTO knownAnomaly : knownAnomalies) {
    if (knownAnomaly.getStartTime() <= windowEnd.getMillis() && knownAnomaly.getEndTime() >= windowStart.getMillis()) {
      overlappedAnomalies.add(knownAnomaly);
    }
  }

  if (overlappedAnomalies.size() > 0) {
    StringBuffer sb = new StringBuffer();
    String separator = "";
    for (MergedAnomalyResultDTO overlappedAnomaly : overlappedAnomalies) {
      sb.append(separator).append(overlappedAnomaly.getStartTime()).append("--").append(overlappedAnomaly.getEndTime());
      separator = ", ";
    }
    LOG.warn("{} merged anomalies overlap with this window {} -- {}. Anomalies: {}", overlappedAnomalies.size(),
        windowStart, windowEnd, sb.toString());
  }
}
 
Example 8
Source File: SuplLppClient.java    From supl-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the number of leap seconds occurred before the input UTC {@link DateTime} instance.
 */
private static int getLeapSecond(DateTime dateTime) {
  int count = 0;
  for (DateTime leapSec : TimeConstants.LEAP_SECOND_LIST) {
    if (leapSec.compareTo(dateTime) <= 0) {
      count++;
    } else {
      break;
    }
  }
  return count;
}
 
Example 9
Source File: BudgetConstructionAccountSelect.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Takes a list of ActionTaken and returns a sorted set ordered by action date
 *
 * @param actionsTaken
 * @return
 */
protected SortedSet<ActionTaken> getSortedActionsTaken(List<ActionTaken> actionsTaken){

    // we need a sorted set of actions taken by action date
    SortedSet<ActionTaken> sortedActionsTaken = new TreeSet<ActionTaken>(new Comparator<ActionTaken>(){
        public int compare(ActionTaken aTaken, ActionTaken bTaken){
            DateTime aActionDate = aTaken.getActionDate();
            DateTime bActionDate = bTaken.getActionDate();
            return aActionDate.compareTo(bActionDate);
        }
    });
    sortedActionsTaken.addAll(actionsTaken);
    return sortedActionsTaken;

}
 
Example 10
Source File: DomainOperationLog.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public int compare(DomainOperationLog domainOperationLog1, DomainOperationLog domainOperationLog2) {
    final DateTime dateTime1 = domainOperationLog1.getWhenDateTime();
    final DateTime dateTime2 = domainOperationLog2.getWhenDateTime();
    int res = dateTime2.compareTo(dateTime1);
    return res;
}
 
Example 11
Source File: FileUtil.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
public int compare(File f1, File f2) {
    // extract datetimes from both files
    DateTime dt1 = DateTimeUtil.parseEmbedded(f1.getName(), pattern, zone);
    DateTime dt2 = DateTimeUtil.parseEmbedded(f2.getName(), pattern, zone);
    // compare these two
    return dt1.compareTo(dt2);
}
 
Example 12
Source File: Trade.java    From bateman with MIT License 5 votes vote down vote up
public void setClose(DateTime close) throws Exception {
    if (close.compareTo(open) <= 0) {
        throw new Exception("Trades must be closed after the open, not before or at the same instant");
    }

    this.close = close;
}
 
Example 13
Source File: MonthAdapter.java    From CustomizableCalendar with MIT License 5 votes vote down vote up
/**
 * Select the day specified if multiple selection mode is not enabled,
 * otherwise adjust the ends of the selection:
 * first end will be set if the day specified is before the first end;
 * last end will be set if the day specified is after the last end;
 *
 * @param dateSelected a DateTime object that represents the day that
 *                     should be selected
 */
@Override
public void setSelected(DateTime dateSelected) {
    if (viewInteractor != null && viewInteractor.hasImplementedSelection()) {
        int itemSelected = viewInteractor.setSelected(multipleSelection, dateSelected);
        switch (itemSelected) {
            case 0:
                notifyFirstSelectionUpdated(dateSelected);
                break;
            case 1:
                notifyLastSelectionUpdated(dateSelected);
                break;
            default:
                return;
        }
    } else {
        if (!multipleSelection) {
            notifyFirstSelectionUpdated(dateSelected);
        } else {
            if (firstSelectedDay != null) {
                int startSelectedCompared = dateSelected.compareTo(firstSelectedDay);
                if (startSelectedCompared < 0) {
                    notifyFirstSelectionUpdated(dateSelected);
                } else if (lastSelectedDay != null) {
                    int endSelectedCompared = dateSelected.compareTo(lastSelectedDay);
                    if ((startSelectedCompared >= 0 && endSelectedCompared < 0) || endSelectedCompared > 0) {
                        notifyLastSelectionUpdated(dateSelected);
                    }
                } else {
                    notifyLastSelectionUpdated(dateSelected);
                }
            } else {
                notifyFirstSelectionUpdated(dateSelected);
            }
        }
    }
    notifyDataSetChanged();
}
 
Example 14
Source File: DateUtils.java    From liteflow with Apache License 2.0 5 votes vote down vote up
/**
 * 获取时间区间内的日期数
 *
 * @param start
 * @param end
 * @return
 */
public static List<Date> getBetweenDates(String start, String end) {
    List<Date> dates = Lists.newLinkedList();
    DateTime startDate = new DateTime(formatToDate(start));
    DateTime endDate = new DateTime(formatToDate(end));
    while (startDate.compareTo(endDate) <= 0) {
        dates.add(startDate.toDate());
        startDate = startDate.plusDays(1);
    }
    return dates;
}
 
Example 15
Source File: DateTimeWritable.java    From spork with Apache License 2.0 4 votes vote down vote up
@Override
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
    DateTime thisValue = new DateTime(readLong(b1, s1));
    DateTime thatValue = new DateTime(readLong(b2, s2));
    return thisValue.compareTo(thatValue);
}
 
Example 16
Source File: SchemaTuple.java    From spork with Apache License 2.0 4 votes vote down vote up
protected int compare(DateTime val, DateTime themVal) {
    return val.compareTo(themVal);
}
 
Example 17
Source File: FileSystemUtils.java    From Cubert with Apache License 2.0 4 votes vote down vote up
public static List<Path> getDurationPaths(FileSystem fs,
                                          Path root,
                                          DateTime startDate,
                                          DateTime endDate,
                                          boolean isDaily,
                                          int hourStep,
                                          boolean errorOnMissing,
                                          boolean useHourlyForMissingDaily) throws IOException
{
    List<Path> paths = new ArrayList<Path>();
    while (endDate.compareTo(startDate) >= 0) {
        Path loc;
        if (isDaily)
            loc = generateDatedPath(root, endDate.getYear(), endDate.getMonthOfYear(), endDate.getDayOfMonth());
        else
            loc = generateDatedPath(root, endDate.getYear(), endDate.getMonthOfYear(), endDate.getDayOfMonth(),
                    endDate.getHourOfDay());

        // Check that directory exists, and contains avro files.
        if (fs.exists(loc) && fs.globStatus(new Path(loc, "*" + "avro")).length > 0) {
            paths.add(loc);
        }

        else {

            loc = generateDatedPath(new Path(root.getParent(),"hourly"), endDate.getYear(),
                    endDate.getMonthOfYear(), endDate.getDayOfMonth());
            if(isDaily && useHourlyForMissingDaily && fs.exists(loc))
            {
                  for (FileStatus hour: fs.listStatus(loc)) {
                      paths.add(hour.getPath());
                  }
            }

            else if (errorOnMissing) {
                throw new RuntimeException("Missing directory " + loc.toString());
            }

        }
        if (hourStep ==24)
            endDate = endDate.minusDays(1);
        else
            endDate = endDate.minusHours(hourStep);
    }
    return paths;
}
 
Example 18
Source File: AbstractCalendarListingWebScript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Returns a Comparator for (re-)sorting events, typically used after
 *  expanding out recurring instances.
 */
protected static Comparator<Map<String, Object>> getEventDetailsSorter()
{
   return new Comparator<Map<String, Object>>() 
   {
      public int compare(Map<String, Object> resultA,
            Map<String, Object> resultB) 
      {
     	 DateTimeFormatter fmtNoTz  = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
     	 DateTimeFormatter fmtTz  =   DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
     	 
     	 String startA = (String)resultA.get(RESULT_START);
     	 String startB = (String)resultB.get(RESULT_START);
     
     	 startA = startA.replace("Z", "+00:00");
     	 startB = startB.replace("Z", "+00:00");
     	 
     	 //check and parse iso8601 date without time zone (All day events are stripped of time zone)
     	 DateTime sa = startA.length()>23?fmtTz.parseDateTime(startA):fmtNoTz.parseDateTime(startA);
     	 DateTime sb = startB.length()>23?fmtTz.parseDateTime(startB):fmtNoTz.parseDateTime(startB);

         int cmp = sa.compareTo(sb);
         if (cmp == 0)
         {
         	String endA = (String)resultA.get(RESULT_END);
         	String endB = (String)resultB.get(RESULT_END);
         	
         	DateTime ea = endA.length()>23?fmtTz.parseDateTime(endA):fmtNoTz.parseDateTime(endA);
         	DateTime eb = endB.length()>23?fmtTz.parseDateTime(endB):fmtNoTz.parseDateTime(endB);

            cmp = ea.compareTo(eb);
            if (cmp == 0)
            {
               String nameA = (String)resultA.get(RESULT_NAME);
               String nameB = (String)resultB.get(RESULT_NAME);
               return nameA.compareTo(nameB);
            }
            return cmp;
         }
         return cmp;
      }
   };
}