Java 类org.joda.time.Minutes 实例源码

项目:keti    文件:AbstractPolicyEvaluationCache.java   
boolean haveConnectorCacheIntervalsLapsed(final AttributeConnectorService localConnectorService,
        final DateTime policyEvalTimestampUTC) {
    DateTime nowUTC = currentDateUTC();

    int decisionAgeMinutes = Minutes.minutesBetween(policyEvalTimestampUTC, nowUTC).getMinutes();

    boolean hasResourceConnectorIntervalLapsed = localConnectorService.isResourceAttributeConnectorConfigured()
            && decisionAgeMinutes >= localConnectorService.getResourceAttributeConnector()
            .getMaxCachedIntervalMinutes();

    boolean hasSubjectConnectorIntervalLapsed = localConnectorService.isSubjectAttributeConnectorConfigured()
            && decisionAgeMinutes >= localConnectorService.getSubjectAttributeConnector()
            .getMaxCachedIntervalMinutes();

    return hasResourceConnectorIntervalLapsed || hasSubjectConnectorIntervalLapsed;
}
项目:exam    文件:SystemRequestHandler.java   
private Map<String, String> getReservationHeaders(Http.RequestHeader request, User user) {
    Map<String, String> headers = new HashMap<>();
    Optional<ExamEnrolment> ongoingEnrolment = getNextEnrolment(user.getId(), 0);
    if (ongoingEnrolment.isPresent()) {
        handleOngoingEnrolment(ongoingEnrolment.get(), request, headers);
    } else {
        DateTime now = new DateTime();
        int lookAheadMinutes = Minutes.minutesBetween(now, now.plusDays(1).withMillisOfDay(0)).getMinutes();
        Optional<ExamEnrolment> upcomingEnrolment = getNextEnrolment(user.getId(), lookAheadMinutes);
        if (upcomingEnrolment.isPresent()) {
            handleUpcomingEnrolment(upcomingEnrolment.get(), request, headers);
        } else if (isOnExamMachine(request)) {
            // User is logged on an exam machine but has no exams for today
            headers.put("x-exam-upcoming-exam", "none");
        }
    }
    return headers;
}
项目:DSSApp    文件:DSSExport.java   
private String get_interval(DateTime largerDatetime, DateTime smallerDateTime) throws HydraClientException{
    int year_diff  = Years.yearsBetween(smallerDateTime, largerDatetime).getYears();
    int month_diff  = Months.monthsBetween(smallerDateTime, largerDatetime).getMonths();
    int day_diff  = Days.daysBetween(smallerDateTime, largerDatetime).getDays();
    int hour_diff = Hours.hoursBetween(smallerDateTime, largerDatetime).getHours();
    int min_diff  = Minutes.minutesBetween(smallerDateTime, largerDatetime).getMinutes();

    if (year_diff > 0){return year_diff+"YEAR";}
    if (month_diff > 0){return month_diff+"MONTH";}
    if (day_diff > 0){return day_diff+"DAY";}
    if (hour_diff > 0){return hour_diff+"HOUR";}
    if (min_diff > 0){return min_diff+"MIN";}

    throw new HydraClientException("Could not compute interval between times " + smallerDateTime.toString() + "and" + largerDatetime.toString());

}
项目:beam    文件:SimplifiedKinesisClient.java   
/**
 * Gets total size in bytes of all events that remain in Kinesis stream between specified
 * instants.
 *
 * @return total size in bytes of all Kinesis events after specified instant
 */
public long getBacklogBytes(final String streamName, final Instant countSince,
    final Instant countTo) throws TransientKinesisException {
  return wrapExceptions(new Callable<Long>() {

    @Override
    public Long call() throws Exception {
      Minutes period = Minutes.minutesBetween(countSince, countTo);
      if (period.isLessThan(Minutes.ONE)) {
        return 0L;
      }

      GetMetricStatisticsRequest request = createMetricStatisticsRequest(streamName,
          countSince, countTo, period);

      long totalSizeInBytes = 0;
      GetMetricStatisticsResult result = cloudWatch.getMetricStatistics(request);
      for (Datapoint point : result.getDatapoints()) {
        totalSizeInBytes += point
            .getSum()
            .longValue();
      }
      return totalSizeInBytes;
    }
  });
}
项目:beam    文件:SimplifiedKinesisClientTest.java   
@Test
public void shouldCountBytesWhenSingleDataPointReturned() throws Exception {
  Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
  Instant countTo = new Instant("2017-04-06T11:00:00.000Z");
  Minutes periodTime = Minutes.minutesBetween(countSince, countTo);
  GetMetricStatisticsRequest metricStatisticsRequest =
      underTest.createMetricStatisticsRequest(STREAM, countSince, countTo, periodTime);
  GetMetricStatisticsResult result = new GetMetricStatisticsResult()
      .withDatapoints(new Datapoint().withSum(1.0));

  given(cloudWatch.getMetricStatistics(metricStatisticsRequest)).willReturn(result);

  long backlogBytes = underTest.getBacklogBytes(STREAM, countSince, countTo);

  assertThat(backlogBytes).isEqualTo(1L);
}
项目:beam    文件:SimplifiedKinesisClientTest.java   
@Test
public void shouldCountBytesWhenMultipleDataPointsReturned() throws Exception {
  Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
  Instant countTo = new Instant("2017-04-06T11:00:00.000Z");
  Minutes periodTime = Minutes.minutesBetween(countSince, countTo);
  GetMetricStatisticsRequest metricStatisticsRequest =
      underTest.createMetricStatisticsRequest(STREAM, countSince, countTo, periodTime);
  GetMetricStatisticsResult result = new GetMetricStatisticsResult()
      .withDatapoints(
          new Datapoint().withSum(1.0),
          new Datapoint().withSum(3.0),
          new Datapoint().withSum(2.0)
      );

  given(cloudWatch.getMetricStatistics(metricStatisticsRequest)).willReturn(result);

  long backlogBytes = underTest.getBacklogBytes(STREAM, countSince, countTo);

  assertThat(backlogBytes).isEqualTo(6L);
}
项目:beam    文件:SimplifiedKinesisClientTest.java   
private void shouldHandleGetBacklogBytesError(
    Exception thrownException,
    Class<? extends Exception> expectedExceptionClass) {
  Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
  Instant countTo = new Instant("2017-04-06T11:00:00.000Z");
  Minutes periodTime = Minutes.minutesBetween(countSince, countTo);
  GetMetricStatisticsRequest metricStatisticsRequest =
      underTest.createMetricStatisticsRequest(STREAM, countSince, countTo, periodTime);

  given(cloudWatch.getMetricStatistics(metricStatisticsRequest)).willThrow(thrownException);
  try {
    underTest.getBacklogBytes(STREAM, countSince, countTo);
    failBecauseExceptionWasNotThrown(expectedExceptionClass);
  } catch (Exception e) {
    assertThat(e).isExactlyInstanceOf(expectedExceptionClass);
  } finally {
    reset(kinesis);
  }
}
项目:calchoochoo    文件:TripSummaryFragment.java   
private void updateSummaryBar() {
  tripSummaryFrom.setText(DataStringUtils.removeCaltrain(possibleTrip.getFirstStopName()));
  tripSummaryTo.setText(DataStringUtils.removeCaltrain(possibleTrip.getLastStopName()));

  tripSummaryPrice.setText(String.format(Locale.getDefault(), "$%.2f", possibleTrip.getPrice()));

  if (possibleTrip.getArrivalTime().getHourOfDay() >= possibleTrip.getDepartureTime().getHourOfDay()) {
    tripSummaryTotalTime.setText(String.format(Locale.getDefault(), "%d min", Minutes.minutesBetween(possibleTrip.getDepartureTime(), possibleTrip.getArrivalTime()).getMinutes()));
  } else {
    tripSummaryTotalTime.setText(String.format(Locale.getDefault(), "%d min", Minutes.minutesBetween(possibleTrip.getDepartureTime().toDateTimeToday(), possibleTrip.getArrivalTime().toDateTimeToday().plusHours(24)).getMinutes()));
  }

  tripSummaryNumber.setText(possibleTrip.getTripShortName());
  tripSummaryDateTime.setText(DateTimeFormat.forPattern("E, MMM d").print(stopDateTime));

  if (possibleTrip.getRouteLongName().contains("Bullet")) {
    tripSummaryImage.setImageDrawable(getActivity().getDrawable(R.drawable.ic_train_bullet));
    tripSummaryImage.setContentDescription(getString(R.string.bullet_train));
  } else {
    tripSummaryImage.setImageDrawable(getActivity().getDrawable(R.drawable.ic_train_local));
    tripSummaryImage.setContentDescription(getString(R.string.local_train));
  }
}
项目:calchoochoo    文件:StopTrainsAdapter.java   
@Override
public void onBindViewHolder(RouteViewHolder holder, int position) {
  PossibleTrain possibleTrain = possibleTrains.get(position);
  DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("h:mma");
  Integer minutes = Minutes.minutesBetween(now, possibleTrain.getDepartureTime().toDateTimeToday()).getMinutes();

  holder.stopCardTrainItemNumber.setText(possibleTrain.getTripShortName());
  holder.stopCardTrainItemTime.setTypeface(null, Typeface.NORMAL);
  holder.stopCardTrainItemBack.setBackgroundColor(ContextCompat.getColor(activity, R.color.cardview_light_background));

  if (possibleTrain.getRouteLongName().contains("Bullet")) {
    holder.stopCardTrainItemImage.setImageDrawable(activity.getDrawable(R.drawable.ic_train_bullet));
  } else {
    holder.stopCardTrainItemImage.setImageDrawable(activity.getDrawable(R.drawable.ic_train_local));
  }

  if (minutes >= 0 && minutes <= 60) {
    holder.stopCardTrainItemTime.setText(String.format(Locale.getDefault(), "in %d min", minutes));
    holder.stopCardTrainItemTime.setTypeface(null, Typeface.ITALIC);
    holder.stopCardTrainItemBack.setBackgroundColor(ContextCompat.getColor(activity, R.color.cardview_light_background));
  } else {
    holder.stopCardTrainItemTime.setText(dateTimeFormatter.print(possibleTrain.getDepartureTime()));
  }
}
项目:bd-codes    文件:TianliActCode.java   
public static void mergeFile() {
    String rootPath = "D:/bdsoft/vko/tianli_act_code";
    String destPath = rootPath + "/all_code.txt";

    File rootDir = new File(rootPath);
    if (rootDir.exists()) {
        File[] fileArr = rootDir.listFiles();
        DateTime start = new DateTime();
        System.out.println("开始:" + start.toLocalDateTime());
        for (File file : fileArr) {
            readFrom(destPath, file);
        }
        DateTime end = new DateTime();
        System.out.println("结束:" + end.toLocalDateTime());
        String msg = String.format("文件合并完毕,耗时:%s分 %s秒", (Minutes.minutesBetween(start, end).getMinutes() % 60),
                (Seconds.secondsBetween(start, end).getSeconds() % 3600));
        System.out.println(msg);
    }
}
项目:bigpicture    文件:HistogramDate.java   
private int computeTimeModeAndDiff(DateTime dmin, DateTime dmax) {
    int diffDay = Days.daysBetween(dmin, dmax).getDays();
    int diffHou = Hours.hoursBetween(dmin, dmax).getHours();
    int diffMin = Minutes.minutesBetween(dmin, dmax).getMinutes();
    int diffSec = Seconds.secondsBetween(dmin, dmax).getSeconds();

    int diff = diffMin;

    guessTimeMode(diffDay, diffHou, diffMin, diffSec);

    if (TimeMode.DAY.equals(timeMode)) {
        diff = diffDay;
    } else if (TimeMode.HOUR.equals(timeMode)) {
        diff = diffHou;
    } else if (TimeMode.MINUTE.equals(timeMode)) {
        diff = diffMin;
    } else if (TimeMode.SECOND.equals(timeMode)) {
        diff = diffSec;
    }

    //consoleDiffs(diffDay, diffHou, diffMin, diffSec, diff);

    return diff;
}
项目:artifactory    文件:CronUtils.java   
/**
 * Checks if the given cron expression interval is less or equals to a certain minimum.
 *
 * @param cronExpression the cron expression to check
 */
public static boolean isCronIntervalLessThanMinimum(String cronExpression) {
    try {
        // If input is empty or invalid simply return false as default
        if (StringUtils.isBlank(cronExpression) || !isValid(cronExpression)) {
            return false;
        }

        CronExpression cron = new CronExpression(cronExpression);
        final Date firstExecution = cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
        final Date secondExecution = cron.getNextValidTimeAfter(firstExecution);

        Minutes intervalMinutes = Minutes.minutesBetween(new DateTime(firstExecution),
                new DateTime(secondExecution));
        return !intervalMinutes.isGreaterThan(MINIMUM_ALLOWED_MINUTES);
    } catch (ParseException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
项目:artifactory    文件:CronUtils.java   
/**
 * Checks if the given cron expression interval is less or equals to a certain minimum.
 *
 * @param cronExpression the cron expression to check
 */
public static boolean isCronIntervalLessThanMinimum(String cronExpression) {
    try {
        // If input is empty or invalid simply return false as default
        if (StringUtils.isBlank(cronExpression) || !isValid(cronExpression)) {
            return false;
        }

        CronExpression cron = new CronExpression(cronExpression);
        final Date firstExecution = cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
        final Date secondExecution = cron.getNextValidTimeAfter(firstExecution);

        Minutes intervalMinutes = Minutes.minutesBetween(new DateTime(firstExecution),
                new DateTime(secondExecution));
        return !intervalMinutes.isGreaterThan(MINIMUM_ALLOWED_MINUTES);
    } catch (ParseException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
项目:welshare    文件:MessageServiceImpl.java   
@Override
@SqlReadonlyTransactional
public Collection<Message> getMissedImportantMessages(User user) {
    List<Message> messages = new ArrayList<Message>();
    for (SocialNetworkService sns : socialNetworkServices) {
        messages.addAll(sns.getMissedIncomingMessages(user));
    }

    DateTime lastLogout = new DateTime(user.getLastLogout());
    // if the last logout was less than an hour ago, assume it was 12 hours ago,
    // so that more messages are displayed (although they might not be actually 'missed')
    if (Minutes.minutesBetween(lastLogout, new DateTime()).getMinutes() < 60) {
        lastLogout = new DateTime().minusHours(12);
    }
    messages.addAll(dao.getIncomingMessages(user,
            followingService.getFollowing(user.getId()), lastLogout));

    filterByImportantMessageThreshold(user.getProfile().getImportantMessageScoreThreshold(),
            user.getProfile().getImportantMessageScoreThresholdRatio(), user, messages);

    messages = filterAndFillMetadata(user, messages,
            Collections.<Message> emptyList(), false, true);

    return messages;
}
项目:twittererer    文件:TimelineConverter.java   
private static String dateToAge(String createdAt, DateTime now) {
    if (createdAt == null) {
        return "";
    }

    DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_TIME_FORMAT);
    try {
        DateTime created = dtf.parseDateTime(createdAt);

        if (Seconds.secondsBetween(created, now).getSeconds() < 60) {
            return Seconds.secondsBetween(created, now).getSeconds() + "s";
        } else if (Minutes.minutesBetween(created, now).getMinutes() < 60) {
            return Minutes.minutesBetween(created, now).getMinutes() + "m";
        } else if (Hours.hoursBetween(created, now).getHours() < 24) {
            return Hours.hoursBetween(created, now).getHours() + "h";
        } else {
            return Days.daysBetween(created, now).getDays() + "d";
        }
    } catch (IllegalArgumentException e) {
        return "";
    }
}
项目:lasso    文件:Alarm.java   
public AlarmResults analyzeTime(List<EGVRecord> egvRecords, GlucoseUnit unit, DateTime downloadTime) {
    AlarmResults results = new AlarmResults();
    if (egvRecords.size() == 0) {
        return results;
    }
    DateTime lastRecordWallTime = egvRecords.get(egvRecords.size() - 1).getWallTime();
    if (preferences.isStaleAlarmEnabled()) {
        if (lastRecordWallTime.plus(ALARM_TIMEAGO_URGENT_MINS).isBeforeNow()) {
            Log.d("Alarm", "Urgent stale data");
            results.setSeverityAtHighest(AlarmSeverity.URGENT);
            results.appendMessage(context.getString(R.string.alarm_timeago_urgent_message, Minutes.minutesBetween(lastRecordWallTime, Instant.now()).getMinutes()));
            results.title = context.getString(R.string.alarm_timeago_standard_title);
        } else if (lastRecordWallTime.plus(ALARM_TIMEAGO_WARN_MINS).isBeforeNow()) {
            Log.d("Alarm", "Warning stale data");
            results.setSeverityAtHighest(AlarmSeverity.WARNING);
            results.appendMessage(context.getString(R.string.alarm_timeago_warn_message, egvRecords.get(egvRecords.size() - 1).getReading().asStr(unit), unit.name(), Minutes.minutesBetween(lastRecordWallTime, Instant.now()).getMinutes()));
            results.title = context.getString(R.string.alarm_timeago_standard_title);
        }
    }
    if (downloadTime.minus(Minutes.minutes(5)).isAfter(lastRecordWallTime)) {
        Log.d("OOR", "Out of range detected");
        results.appendMessage(context.getString(R.string.alarm_out_of_range_message, Minutes.minutesBetween(lastRecordWallTime, Instant.now()).getMinutes()));
    }
    return results;
}
项目:lasso    文件:NightscoutMonitor.java   
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(SNOOZE_INTENT)) {
        if (preferences.getAlarmStrategy() == 0) {
            for (String url : preferences.getRestApiBaseUris()) {
                ackAlarm(url);
            }

        } else {
            Log.w(TAG, "Snoozing per request");
            alarm.alarmSnooze(Minutes.minutes(30).toStandardDuration().getMillis());
        }
    } else if (intent.getAction().equals(MQTT_QUERY_STATUS_INTENT)) {
        Intent responseIntent = new Intent(MQTT_RESPONSE_STATUS_INTENT);
        responseIntent.putExtra(MQTT_STATUS_EXTRA_FIELD, mqttManager.isConnected());
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(responseIntent);
    }
}
项目:jfixture    文件:BaseSingleFieldPeriodRelay.java   
@Override
public Object create(Object request, SpecimenContext context) {

    if (!(request instanceof SpecimenType)) {
        return new NoSpecimen();
    }

    SpecimenType type = (SpecimenType) request;
    if (!BaseSingleFieldPeriod.class.isAssignableFrom(type.getRawType())) {
        return new NoSpecimen();
    }

    Duration duration = (Duration) context.resolve(Duration.class);
    if (type.equals(Seconds.class)) return Seconds.seconds(Math.max(1, (int) duration.getStandardSeconds()));
    if (type.equals(Minutes.class)) return Minutes.minutes(Math.max(1, (int) duration.getStandardMinutes()));
    if (type.equals(Hours.class)) return Hours.hours(Math.max(1, (int) duration.getStandardHours()));

    if (type.equals(Days.class)) return Days.days(Math.max(1, (int) duration.getStandardDays()));
    if (type.equals(Weeks.class)) return Weeks.weeks(Math.max(1, (int) duration.getStandardDays() / 7));
    if (type.equals(Months.class)) return Months.months(Math.max(1, (int) duration.getStandardDays() / 30));
    if (type.equals(Years.class)) return Years.years(Math.max(1, (int) duration.getStandardDays() / 365));

    return new NoSpecimen();
}
项目:Crosslinks    文件:ProcessorController.java   
private StartableStatus getStartStatus() {
    if (Mode.DISABLED.equals(getMode())) {
        return new StartableStatus(false, "in mode " + getMode().toString());
    }
    else if (isActive()) {
        return new StartableStatus(false, "currently active");
    }
    else if (!isOk()) {
        int minutesBetween = Minutes.minutesBetween(new DateTime(ended), new DateTime()).getMinutes();
        return new StartableStatus(minutesBetween > pauseOnAbort, "waited " + minutesBetween + " of " + pauseOnAbort + " minutes since " + getStatus());
    }
    else if (isForced()) {
        return new StartableStatus(true, "isForced");
    }
    else if (getDateLastCrawled() == null) {
        return new StartableStatus(true, "never finished crawl before");
    }
    else {
        int daysBetween = Days.daysBetween(new DateTime(getDateLastCrawled()), new DateTime()).getDays();
        return  new StartableStatus(daysBetween > staleDays, "waited " + daysBetween + " of " + staleDays + " days");
    }
}
项目:hawkular-metrics    文件:RepeatingTrigger.java   
private RepeatingTrigger(Long triggerTime, Long interval, Long delay, Integer repeatCount) {
    if (triggerTime != null) {
        this.triggerTime = getTimeSlice(triggerTime, standardMinutes(1));
    }
    else if (interval == null && delay == null) {
        this.triggerTime = currentMinute().plusMinutes(1).getMillis();
    }

    this.interval = interval;
    this.delay = delay == null ? Minutes.ONE.toStandardDuration().getMillis() : delay;
    this.repeatCount = repeatCount;
    this.executionCount = 1;

    if (this.triggerTime == null) {
        this.triggerTime = getTimeSlice(now.get().getMillis() + this.delay, standardMinutes(1));
    }
}
项目:hawkular-metrics    文件:JobExecutionTest.java   
@Test
public void executeJobThatFailsAndRetriesAfterDelay() throws Exception {
    Trigger trigger = new SingleExecutionTrigger.Builder().withDelay(1, TimeUnit.MINUTES).build();
    DateTime timeSlice = new DateTime(trigger.getTriggerTime());
    JobDetails jobDetails = createJobDetails(randomUUID(), "Failed Job", "Failed Job", emptyMap(), trigger);

    AtomicInteger attempts = new AtomicInteger();
    Func1<JobDetails, Completable> job = details -> {
        if (attempts.getAndIncrement() == 0) {
            return Completable.error(new Exception());
        }
        return Completable.complete();
    };
    Func2<JobDetails, Throwable, RetryPolicy> retry = (details, throwable) ->
            () -> Minutes.ONE.toStandardDuration().getMillis();

    jobScheduler.register(jobDetails.getJobType(), job, retry);

    scheduleJob(jobDetails);

    waitForSchedulerToFinishTimeSlice(timeSlice);
    waitForSchedulerToFinishTimeSlice(timeSlice.plusMinutes(1));

    assertEquals(attempts.get(), 2);
}
项目:WHNewsReader-Android    文件:MyDateUtils.java   
public static String TimeFromTodayAccuracyToTheMinute(String date){
    String Time = "";
    DateTime StoryTime = new DateTime(date);
    DateTime NowTime = new DateTime();
    int minutes = Minutes.minutesBetween(StoryTime, NowTime).getMinutes();
    int hours = Hours.hoursBetween(StoryTime, NowTime).getHours();
    int days = Days.daysBetween(StoryTime, NowTime).getDays();
    if(days > 0){
        Time  = Time + " " + days + " d";
    }
    if(BelowADay(hours) > 0){
        int timeHours = BelowADay(hours);
        Time  = Time + " " + timeHours + " h";
    }
    if(BelowAHour(minutes) > 0){
        int timeMins = BelowAHour(minutes);
        Time  = Time + " " + timeMins + " m";
    }

    Time = Time + " ago.";
    if(Time.length()==5){
        Time = "less then a minute ago.";
    }
    return Time;
}
项目:java-util-examples    文件:CalculateDateTimeDifference.java   
@Test
public void difference_between_two_dates_joda () {

    DateTime sinceGraduation = new DateTime(1984, 6, 4, 0, 0, GregorianChronology.getInstance());
    DateTime currentDate = new DateTime(); //current date

    Days diffInDays = Days.daysBetween(sinceGraduation, currentDate);
    Hours diffInHours = Hours.hoursBetween(sinceGraduation, currentDate);
    Minutes diffInMinutes = Minutes.minutesBetween(sinceGraduation, currentDate);
    Seconds seconds = Seconds.secondsBetween(sinceGraduation, currentDate);

    logger.info(diffInDays.getDays());
    logger.info(diffInHours.getHours());
    logger.info(diffInMinutes.getMinutes());
    logger.info(seconds.getSeconds());

    assertTrue(diffInDays.getDays() >= 10697);
    assertTrue(diffInHours.getHours() >= 256747);
    assertTrue(diffInMinutes.getMinutes() >= 15404876);
    assertTrue(seconds.getSeconds() >= 924292577);

}
项目:codeine    文件:CollectionTypeGetter.java   
public List<AlertsCollectionType> getCollectionType(DateTime dateTime) {
    if (!dateTime.isAfter(lastGet)){
        throw new IllegalArgumentException("collection is not after previous " + lastGet + ", " + dateTime);
    }
    lastGet = dateTime;
    if (dateTime.getHourOfDay() >= TIME_WINDOW_TO_REPORT_DAY_MIN 
            && dateTime.getHourOfDay() <= TIME_WINDOW_TO_REPORT_DAY_MAX && 
            Hours.hoursBetween(lastDailyCollection, dateTime).getHours() > reportingWindowDay()){
        log.info("daily mail collection");
        lastDailyCollection = dateTime;
        lastHourlyCollection = dateTime;
        return Lists.newArrayList(AlertsCollectionType.Immediately, AlertsCollectionType.Hourly, AlertsCollectionType.Daily);
    }
    if (dateTime.getMinuteOfHour() <= TIME_WINDOW_TO_REPORT_HOUR && Minutes.minutesBetween(lastHourlyCollection, dateTime).getMinutes() > TIME_WINDOW_TO_REPORT_HOUR){
        log.info("hourly mail collection");
        lastHourlyCollection = dateTime;
        return Lists.newArrayList(AlertsCollectionType.Immediately, AlertsCollectionType.Hourly);
    }
    return Lists.newArrayList(AlertsCollectionType.Immediately);
}
项目:axelor-business-suite    文件:TimesheetServiceImpl.java   
@Transactional
public void insertTSLine(ActionRequest request, ActionResponse response){

    User user = AuthUtils.getUser();
    ProjectTask projectTask = Beans.get(ProjectTaskRepository.class).find(new Long(request.getData().get("project").toString()));
    Product product = Beans.get(ProductRepository.class).find(new Long(request.getData().get("activity").toString()));
    LocalDate date = new LocalDate(request.getData().get("date").toString());
    if(user != null){
        Timesheet timesheet = Beans.get(TimesheetRepository.class).all().filter("self.statusSelect = 1 AND self.user.id = ?1", user.getId()).order("-id").fetchOne();
        if(timesheet == null){
            timesheet = createTimesheet(user, date, date);
        }
        BigDecimal minutes = new BigDecimal(Minutes.minutesBetween(new LocalTime(0,0), new LocalTime(request.getData().get("duration").toString())).getMinutes());
        createTimesheetLine(projectTask, product, user, date, timesheet, minutes, request.getData().get("comments").toString());

        Beans.get(TimesheetRepository.class).save(timesheet);
    }
}
项目:sunposition    文件:TestSunAlgorithm.java   
private void assertTimeEquals(final String location,
                              final int type,
                              final int expectedHour,
                              final int expectedMinute,
                              final double riseset[])
{
  final int MINUTES_DELTA = 1;

  final double actualHours = riseset[type];
  final String typeString = type == SunPositionAlgorithm.SET? "sunset"
                                                            : "sunrise";

  final LocalTime expectedTime = new LocalTime(expectedHour, expectedMinute);
  final LocalTime actualTime = toLocalTime(actualHours);
  final Minutes minutes = Minutes.minutesBetween(expectedTime, actualTime);

  String message = location + " " + typeString + ": expected " + expectedTime
                   + "; actual " + actualTime;
  System.out.println(message);
  assertTrue(message, Math.abs(minutes.getMinutes()) <= MINUTES_DELTA);
}
项目:cloudconductor-server    文件:AgentImpl.java   
@Override
@Transactional
public Set<String> getAliveAgents() {
    List<EHost> hosts = this.dhost.findList();
    DateTime now = new DateTime();
    Set<String> result = new HashSet<>();
    for (EHost host : hosts) {
        DateTime dt = new DateTime(host.getLastSeen());
        int diff = Minutes.minutesBetween(dt, now).getMinutes();

        if (diff < AgentImpl.MAX_TIMEOUT_HOST) {
            result.add(host.getName());
        }
    }
    return result;
}
项目:cloudconductor-server    文件:AgentImpl.java   
/**
 * @param template
 * @param host
 */
private boolean sendPackageChanges(ETemplate template, EHost host) {
    DateTime now = DateTime.now();
    int maxHostsOnUpdate = template.getHosts().size() / 2;
    int hostsOnUpdate = 0;
    if ((template.getSmoothUpdate() == null) || !template.getSmoothUpdate() || (maxHostsOnUpdate < 1)) {
        return true;
    }
    if (host.getStartedUpdate() != null) {
        return true;
    }
    for (EHost h : template.getHosts()) {
        if (h.getStartedUpdate() != null) {
            int timeElapsed = Minutes.minutesBetween(new DateTime(h.getStartedUpdate()), now).getMinutes();
            if (timeElapsed > AgentImpl.MAX_UPDATE_THRESHOLD) {
                continue;
            }
            hostsOnUpdate++;
        }
    }
    if (maxHostsOnUpdate > hostsOnUpdate) {
        return true;
    }
    return false;
}
项目:parkandrideAPI    文件:UtilizationDao.java   
@Transactional(readOnly = true, isolation = READ_COMMITTED, propagation = MANDATORY)
@Override
public List<Utilization> findUtilizationsWithResolution(UtilizationKey utilizationKey, DateTime start, DateTime end, Minutes resolution) {
    ArrayList<Utilization> results = new ArrayList<>();
    Optional<Utilization> first = findUtilizationAtInstant(utilizationKey, start);
    try (CloseableIterator<Utilization> rest = findUtilizationsBetween(utilizationKey, start, end)) {
        LinkedList<Utilization> utilizations = Stream.concat(
                StreamUtil.asStream(first),
                StreamUtil.asStream(rest))
                .collect(Collectors.toCollection(LinkedList::new));

        Utilization current = null;
        for (DateTime instant = start; !instant.isAfter(end); instant = instant.plus(resolution)) {
            while (!utilizations.isEmpty() && !utilizations.getFirst().timestamp.isAfter(instant)) {
                current = utilizations.removeFirst();
            }
            if (current != null) {
                current.timestamp = instant;
                results.add(current.copy());
            }
        }
    }
    return results;
}
项目:parkandrideAPI    文件:UtilizationDaoTest.java   
@Test
public void findUtilizationsWithResolution_repeats_the_previous_utilization_at_resolution_intervals() {
    DateTime start = new DateTime(2000, 1, 1, 12, 0);
    DateTime end = start.plusHours(1);
    Minutes resolution = Minutes.minutes(30);

    Utilization u1 = newUtilization(facilityId, start.minusHours(1), 100, 100);
    utilizationDao.insertUtilizations(asList(u1));
    UtilizationKey utilizationKey = u1.getUtilizationKey();

    List<Utilization> results = utilizationDao.findUtilizationsWithResolution(utilizationKey, start, end, resolution);
    assertThat(results).containsExactly(
            newUtilization(facilityId, start, 100, 100),
            newUtilization(facilityId, start.plus(resolution), 100, 100),
            newUtilization(facilityId, end, 100, 100));
}
项目:parkandrideAPI    文件:UtilizationDaoTest.java   
@Test
public void findUtilizationsWithResolution_availability_is_updated_when_there_are_new_utilizations() {
    DateTime start = new DateTime(2000, 1, 1, 12, 0);
    DateTime end = start.plusHours(1);
    Minutes resolution = Minutes.minutes(30);

    Utilization u1 = newUtilization(facilityId, start, 100, 100);
    Utilization u2 = newUtilization(facilityId, start.plus(resolution), 200, 200);
    utilizationDao.insertUtilizations(asList(u1, u2));
    UtilizationKey utilizationKey = u1.getUtilizationKey();

    List<Utilization> results = utilizationDao.findUtilizationsWithResolution(utilizationKey, start, end, resolution);
    assertThat(results).containsExactly(
            newUtilization(facilityId, start, 100, 100),
            newUtilization(facilityId, start.plus(resolution), 200, 200),
            newUtilization(facilityId, end, 200, 200));
}
项目:GowerTides    文件:Tide.java   
public String getTimeDifference(Calendar cal){

        int h_diff = Math.abs(Hours.hoursBetween(new DateTime(time.getTime()), new DateTime(cal.getTime())).getHours() % 24);
        int m_diff = Math.abs(Minutes.minutesBetween(new DateTime(time.getTime()), new DateTime(cal.getTime())).getMinutes() % 60);

        String h_diff_s = h_diff+"";
        String m_diff_s = m_diff+"";
        if(m_diff < 10){
            m_diff_s = "0"+m_diff_s;
        }

        boolean negative = true; // negative if time of tide BEHIND current time
        long milli_diff = cal.getTime().getTime() - time.getTime().getTime();
        if(milli_diff < 0){
            negative = false;
        }

        if(negative){
            return "-"+h_diff_s+":"+m_diff_s;
        }
        else{
            return "+"+h_diff_s+":"+m_diff_s;
        }
    }
项目:jtrade    文件:TestTimeSeries.java   
@Test(dataProvider = "testTimeSeriesProvider")
public void testTimeSeriesFreq(Class<TimeSeries> cls) throws Exception {
    TimeSeries ts1 = cls.getConstructor(DateTime.class, Period.class, int.class, double.class).newInstance(new DateTime(2013, 1, 1, 0, 0, 0, 0),
            Days.ONE.toPeriod(), 365, 0.0);
    TimeSeries ts2 = cls.getConstructor(DateTime[].class, double[].class).newInstance(
            new DateTime[] { new DateTime(2013, 1, 31, 0, 0, 0, 0), new DateTime(2013, 2, 28, 0, 0, 0, 0), new DateTime(2013, 3, 31, 0, 0, 0, 0),
                    new DateTime(2013, 4, 30, 0, 0, 0, 0), new DateTime(2013, 5, 31, 0, 0, 0, 0), new DateTime(2013, 6, 30, 0, 0, 0, 0),
                    new DateTime(2013, 7, 31, 0, 0, 0, 0), new DateTime(2013, 8, 31, 0, 0, 0, 0), new DateTime(2013, 9, 30, 0, 0, 0, 0),
                    new DateTime(2013, 10, 31, 0, 0, 0, 0), new DateTime(2013, 11, 30, 0, 0, 0, 0), new DateTime(2013, 12, 31, 0, 0, 0, 0) },
            new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 });

    assertEquals(ts2, ts1.asFreq(TimeSeries.FreqMethod.END_OF_MONTH));
    assertEquals(ts2.last(1), ts1.asFreq(TimeSeries.FreqMethod.END_OF_YEAR));
    TimeSeries ts3 = cls.getConstructor(DateTime.class, Period.class, int.class, double.class).newInstance(new DateTime(2013, 1, 1, 0, 0, 0, 0),
            Minutes.ONE.toPeriod(), 1440 * 2, 0.0);
    TimeSeries ts4 = cls.getConstructor(DateTime[].class, double[].class).newInstance(
            new DateTime[] { new DateTime(2013, 1, 1, 23, 59, 0, 0), new DateTime(2013, 1, 2, 23, 59, 0, 0) }, new double[] { 0.0, 0.0 });
    assertEquals(ts4, ts3.asFreq(TimeSeries.FreqMethod.END_OF_DAY));
}
项目:jtrade    文件:TestTimeSeries.java   
@Test(dataProvider = "testTimeSeriesProvider")
public void testTimeSeriesStats(Class<TimeSeries> cls) throws Exception {
    TimeSeries ts = cls.getConstructor(Map.class).newInstance(map);

    assertEquals(100.0, ts.min());
    assertEquals(110.0, ts.max());
    assertEquals(315.0, ts.sum());
    assertEquals(105.0, ts.mean());
    assertEquals(105.0, ts.median());
    assertEquals(5.0, ts.std());
    assertEquals(25.0, ts.var());
    assertEquals(1.0, ts.corr(ts));
    assertEquals(-1.0, ts.corr(ts.mul(-1.0)));
    assertEquals(1.0, ts.autoCorr(0));
    assertEqualsArray(new double[] { -1.0, 0.0, 1.0 }, ts.standardize().data());
    assertEqualsArray(new double[] { 100.0, 205.0, 315.0 }, ts.cumsum().data());
    assertEqualsArray(new double[] { 0.0, 5.0, 5.0 }, ts.diff(1).data());
    assertEquals(0.048790164169432, ts.logReturn(1).data()[1], 1.0E-9);
    assertEquals(0.05, ts.arithReturn(1).data()[1], 1.0E-9);

    TimeSeries ts2 = cls.getConstructor(DateTime.class, Period.class, double[].class).newInstance(
            new DateTime(2013, 1, 1, 0, 0, 0, 0), Minutes.ONE.toPeriod(), new double[] { 2.0, 1.0, 3.0, 5.0, 4.0, 6.0 });
    assertEquals(5.0, ts2.last(3).median());
}
项目:levelup-java-examples    文件:CalculateDateTimeDifference.java   
@Test
public void difference_between_two_dates_joda () {

    DateTime sinceGraduation = new DateTime(1984, 6, 4, 0, 0, GregorianChronology.getInstance());
    DateTime currentDate = new DateTime(); //current date

    Days diffInDays = Days.daysBetween(sinceGraduation, currentDate);
    Hours diffInHours = Hours.hoursBetween(sinceGraduation, currentDate);
    Minutes diffInMinutes = Minutes.minutesBetween(sinceGraduation, currentDate);
    Seconds seconds = Seconds.secondsBetween(sinceGraduation, currentDate);

    logger.info(diffInDays.getDays());
    logger.info(diffInHours.getHours());
    logger.info(diffInMinutes.getMinutes());
    logger.info(seconds.getSeconds());

    assertTrue(diffInDays.getDays() >= 10697);
    assertTrue(diffInHours.getHours() >= 256747);
    assertTrue(diffInMinutes.getMinutes() >= 15404876);
    assertTrue(seconds.getSeconds() >= 924292577);

}
项目:PocketKnell    文件:KnellActivity.java   
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_knell);
    ButterKnife.bind(this);

    Birthday birthday = getBirthdayManager().get();
    DateTime birDateTime = new DateTime(birthday.year, birthday.month, birthday.day, 0, 0);
    Days days = Days.daysBetween(birDateTime, DateTime.now());
    Hours hours = Hours.hoursBetween(birDateTime, DateTime.now());
    Minutes minutes = Minutes.minutesBetween(birDateTime, DateTime.now());
    Weeks weeks = Weeks.weeksBetween(birDateTime, DateTime.now());
    Years years = Years.yearsBetween(birDateTime, DateTime.now());
    Months months = Months.monthsBetween(birDateTime, DateTime.now());

    Timber.d("onCreate: 年:%d", years.getYears());
    Timber.d("onCreate: 月:%d", months.getMonths());
    Timber.d("onCreate: 周:%d", weeks.getWeeks());
    Timber.d("onCreate: 天数为:%d", days.getDays());
    Timber.d("onCreate: 小时数为:%d", hours.getHours());
    Timber.d("onCreate: 分钟数为:%d", minutes.getMinutes());

    tvYear.setText(String.valueOf(years.getYears()));
    tvMonth.setText(String.valueOf(months.getMonths()));
    tvWeek.setText(String.valueOf(weeks.getWeeks()));
    tvDay.setText(String.valueOf(days.getDays()));
    tvHour.setText(String.valueOf(hours.getHours()));
    tvMinute.setText(String.valueOf(minutes.getMinutes()));
}
项目:exam    文件:SessionController.java   
private Reservation getUpcomingExternalReservation(String eppn) {
    DateTime now = AppUtil.adjustDST(new DateTime());
    int lookAheadMinutes = Minutes.minutesBetween(now, now.plusDays(1).withMillisOfDay(0)).getMinutes();
    DateTime future = now.plusMinutes(lookAheadMinutes);
    List<Reservation> reservations = Ebean.find(Reservation.class).where()
            .eq("externalUserRef", eppn)
            .isNotNull("externalRef")
            .le("startAt", future)
            .gt("endAt", now)
            .orderBy("startAt")
            .findList();
    return reservations.isEmpty() ? null : reservations.get(0);
}
项目:healthvault-java-sdk    文件:HealthVaultRestClient.java   
public void tokenRefresh(Connection connection){
        if (Minutes.minutesBetween(DateTime.now(), mLastRefreshedSessionCredential).isGreaterThan(Minutes.minutes(mSessionCredentialCallThresholdMinutes))) {
            connection.getAuthenticator().authenticate(connection, true);
            mLastRefreshedSessionCredential = DateTime.now();
            mSettings.setSessionExpiration();
        }
}
项目:MyHitchhikingSpots-for-Android    文件:GoogleLocationTrackingActivity.java   
protected void GotARideShortcut() {
    try {
        //Get currentSpot and update it
        MyHitchhikingSpotsApplication appContext = ((MyHitchhikingSpotsApplication) getApplicationContext());
        mCurrentSpot = appContext.getCurrentSpot();

        if (mCurrentSpot == null || mCurrentSpot.getIsWaitingForARide() == null || !mCurrentSpot.getIsWaitingForARide()) {
            if (mCurrentLocation == null)
                return;
            mCurrentSpot = new Spot();
            mCurrentSpot.setIsHitchhikingSpot(true);
            mCurrentSpot.setStartDateTime(new Date());
            mCurrentSpot.setIsWaitingForARide(true);
            mCurrentSpot.setIsDestination(false);
            mCurrentSpot.setLatitude(mCurrentLocation.getLatitude());
            mCurrentSpot.setLongitude(mCurrentLocation.getLongitude());
            mCurrentSpot.setIsPartOfARoute(true);
        } else {
            DateTime date = new DateTime(mCurrentSpot.getStartDateTime());
            Integer waiting_time = Minutes.minutesBetween(date, DateTime.now()).getMinutes();

            mCurrentSpot.setWaitingTime(waiting_time);
            mCurrentSpot.setAttemptResult(Constants.ATTEMPT_RESULT_GOT_A_RIDE);
            mCurrentSpot.setIsWaitingForARide(false);

                //mCurrentSpot.setHitchability(my_location_fragment.getSelectedHitchability());
        }

        //Persist on DB
        DaoSession daoSession = appContext.getDaoSession();
        SpotDao spotDao = daoSession.getSpotDao();
        spotDao.insertOrReplace(mCurrentSpot);
        ((MyHitchhikingSpotsApplication) getApplicationContext()).setCurrentSpot(mCurrentSpot);
        Toast.makeText(getApplicationContext(), R.string.spot_saved_successfuly, Toast.LENGTH_LONG).show();

    } catch (Exception ex) {
        Crashlytics.logException(ex);
        ((BaseActivity) getParent()).showErrorAlert("Save shortcut", getString(R.string.shortcut_save_button_failed));
    }
}
项目:azkaban    文件:Schedule.java   
public static ReadablePeriod parsePeriodString(String periodStr) {
  ReadablePeriod period;
  char periodUnit = periodStr.charAt(periodStr.length() - 1);
  if (periodUnit == 'n') {
    return null;
  }

  int periodInt =
      Integer.parseInt(periodStr.substring(0, periodStr.length() - 1));
  switch (periodUnit) {
  case 'M':
    period = Months.months(periodInt);
    break;
  case 'w':
    period = Weeks.weeks(periodInt);
    break;
  case 'd':
    period = Days.days(periodInt);
    break;
  case 'h':
    period = Hours.hours(periodInt);
    break;
  case 'm':
    period = Minutes.minutes(periodInt);
    break;
  case 's':
    period = Seconds.seconds(periodInt);
    break;
  default:
    throw new IllegalArgumentException("Invalid schedule period unit '"
        + periodUnit);
  }

  return period;
}