Example usage for org.joda.time Minutes minutesBetween

List of usage examples for org.joda.time Minutes minutesBetween

Introduction

In this page you can find the example usage for org.joda.time Minutes minutesBetween.

Prototype

public static Minutes minutesBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Minutes representing the number of whole minutes between the two specified partial datetimes.

Usage

From source file:com.axelor.studio.service.wkf.WkfTrackingService.java

License:Open Source License

/**
 * Method add new WkfTrackingLine in WkfTracking for given status if that
 * status is not last status added.//from w ww . ja  v  a 2  s .  com
 * 
 * @param wkfTracking
 *            WkfTracking to update with new line.
 * @param status
 *            Status to check for update.
 * @return WkfTrackingLine created or return null if status not changed.
 */
@Transactional
public WkfTrackingLine updateTrackingLine(WkfTracking wkfTracking, String status) {

    WkfTrackingLine trackingLine = trackingLineRepo.all().filter("self.wkfTracking = ?1", wkfTracking)
            .fetchOne();

    if (trackingLine == null || !trackingLine.getStatus().equals(status)) {

        LocalDateTime now = new LocalDateTime();

        if (trackingLine != null) {
            oldStatus = trackingLine.getStatus();
            LocalDateTime lastUpdated = trackingLine.getCreatedOn();
            Minutes minutes = Minutes.minutesBetween(lastUpdated, now);
            log.debug("Minutes between {} and {} : {}", lastUpdated, now, minutes.getMinutes());
            durationHrs = new BigDecimal(minutes.getMinutes()).divide(new BigDecimal(60), 2,
                    RoundingMode.HALF_UP);
            log.debug("Hours between {} and {} : {}", lastUpdated, now, durationHrs);
            trackingLine.setTimeSpent(durationHrs);
            trackingLineRepo.save(trackingLine);
        }

        trackingLine = new WkfTrackingLine();
        trackingLine.setWkfTracking(wkfTracking);
        trackingLine.setStatus(status);
        trackingLine.setWkfTracking(wkfTracking);
        return trackingLineRepo.save(trackingLine);
    }

    return null;
}

From source file:com.cisco.dvbu.ps.utils.date.DateDiffDate.java

License:Open Source License

/**
 * Called to invoke the stored procedure.  Will only be called a
 * single time per instance.  Can throw CustomProcedureException or
 * SQLException if there is an error during invoke.
 *///from  w w w  .ja v  a  2s .  c  o m
public void invoke(Object[] inputValues) throws CustomProcedureException, SQLException {
    java.util.Date startDate = null;
    java.util.Date endDate = null;
    Calendar startCal = null;
    Calendar endCal = null;
    DateTime startDateTime = null;
    DateTime endDateTime = null;
    String datePart = null;
    long dateLength = 0;

    try {
        result = null;
        if (inputValues[0] == null) {
            result = new Long(dateLength);
            return;
        }

        if (inputValues[1] == null) {
            result = new Long(dateLength);
            return;
        }

        if (inputValues[2] == null) {
            result = new Long(dateLength);
            return;
        }

        datePart = (String) inputValues[0];
        startDate = (java.util.Date) inputValues[1];
        startCal = Calendar.getInstance();
        startCal.setTime(startDate);

        endDate = (java.util.Date) inputValues[2];
        endCal = Calendar.getInstance();
        endCal.setTime(endDate);

        startDateTime = new DateTime(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH) + 1,
                startCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0, 0);
        endDateTime = new DateTime(endCal.get(Calendar.YEAR), endCal.get(Calendar.MONTH) + 1,
                endCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0, 0);

        if (datePart.equalsIgnoreCase("second")) {
            Seconds seconds = Seconds.secondsBetween(startDateTime, endDateTime);
            dateLength = seconds.getSeconds();
        }

        if (datePart.equalsIgnoreCase("minute")) {
            Minutes minutes = Minutes.minutesBetween(startDateTime, endDateTime);
            dateLength = minutes.getMinutes();
        }

        if (datePart.equalsIgnoreCase("hour")) {
            Hours hours = Hours.hoursBetween(startDateTime, endDateTime);
            dateLength = hours.getHours();
        }

        if (datePart.equalsIgnoreCase("day")) {
            Days days = Days.daysBetween(startDateTime, endDateTime);
            dateLength = days.getDays();
        }

        if (datePart.equalsIgnoreCase("week")) {
            Weeks weeks = Weeks.weeksBetween(startDateTime, endDateTime);
            dateLength = weeks.getWeeks();
        }

        if (datePart.equalsIgnoreCase("month")) {
            Months months = Months.monthsBetween(startDateTime, endDateTime);
            dateLength = months.getMonths();
        }

        if (datePart.equalsIgnoreCase("year")) {
            Years years = Years.yearsBetween(startDateTime, endDateTime);
            dateLength = years.getYears();
        }

        result = new Long(dateLength);
    } catch (Throwable t) {
        throw new CustomProcedureException(t);
    }
}

From source file:com.enitalk.controllers.OpentokSessionController.java

@RequestMapping(method = RequestMethod.GET, value = "/session/teacher/{id}", produces = "text/html")
@ResponseBody/*w w w  .ja v  a2s  .c  o m*/
public byte[] sessionTeacher(@PathVariable String id, HttpServletResponse res, boolean requireUrl)
        throws IOException {
    byte[] out = null;
    try {
        Query q = Query.query(Criteria.where("ii").is(id).andOperator(Criteria.where("status").is(2)));
        logger.info("Looking for teacher event {}", id);
        HashMap ev = mongo.findOne(q, HashMap.class, "events");
        if (ev == null) {
            return "Sorry, no such event found.".getBytes();
        }

        Date date = (Date) ev.get("dd");
        DateTime scheduled = new DateTime(date.getTime()).toDateTime(DateTimeZone.UTC);
        DateTime nnow = new DateTime(DateTimeZone.UTC);
        int bt = Minutes.minutesBetween(nnow, scheduled).getMinutes();

        logger.info("Scheduled joda {} diff {}", scheduled, bt);

        ObjectNode evJson = jackson.convertValue(ev, ObjectNode.class);

        if (bt > 6) {
            String rs = "You're a bit early, please visit this page at "
                    + scheduled.minusMinutes(5).toString("yyyy/MM/dd HH:mm:ss 'GMT'");
            return rs.getBytes();
        }
        //            
        if (bt < -62) {
            String rs = "It seems that your session has already ended or expired. Please, contact us at ceo@enitalk.com if there seems to be a mistake.";
            return rs.getBytes();
        }

        String url = s3Cache.get(evJson);

        if (!requireUrl) {
            url += "?dest=" + evJson.at("/ii").asText() + "&i=" + evJson.path("ii").asText();
            String signed = signer.signUrl(url, new DateTime().plusMinutes(80));
            res.sendRedirect(signed);
        } else {
            return url.getBytes();
        }
    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
        return "Oops. Something went wrong. Contact us at ceo@enitalk.com".getBytes();
    }
    return out;
}

From source file:com.francelabs.datafari.alerts.AlertsManager.java

License:Apache License

/**
 * Calculate the difference in minutes between the current date time and the
 * provided scheduled one, according to the frequency
 *
 * @param frequency//from  ww  w .j  ava  2s  .c om
 *          the frequency of the scheduled date time
 * @param scheduledDate
 *          the initial scheduled date time that the user has typed in the
 *          admin UI
 * @return the difference in minutes between the current date time and the
 *         next scheduled one
 */
private long calculateDelays(final String frequency, final DateTime scheduledDate) {
    long diff = 0L;
    final Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    final DateTime currentDateTime = new DateTime(cal.getTime());
    DateTime scheduledDateTimeUpdate;

    switch (frequency.toLowerCase()) {
    case "hourly":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is earlier than the scheduled one, simply calculate
        // the difference in minutes, otherwise create the next scheduled
        // date and calculate the difference
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.HOUR_OF_DAY, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        diff = Minutes.minutesBetween(currentDateTime, scheduledDateTimeUpdate).getMinutes();
        break;

    case "daily":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, scheduledDate.getHourOfDay());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is earlier than the scheduled one, simply calculate
        // the difference in minutes, otherwise create the next scheduled
        // date and calculate the difference
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        diff = Minutes.minutesBetween(currentDateTime, scheduledDateTimeUpdate).getMinutes();
        break;

    case "weekly":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.DAY_OF_WEEK, scheduledDate.getDayOfWeek() + 1); // +1
        // =
        // diff
        // between
        // Joda
        // and
        // Calendar
        cal.set(Calendar.HOUR_OF_DAY, scheduledDate.getHourOfDay());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is earlier than the scheduled one, simply calculate
        // the difference in minutes, otherwise create the next scheduled
        // date and calculate the difference
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.WEEK_OF_YEAR, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        diff = Minutes.minutesBetween(currentDateTime, scheduledDateTimeUpdate).getMinutes();
        break;

    default:
        break;
    }

    return diff;
}

From source file:com.ge.predix.acs.policy.evaluation.cache.AbstractPolicyEvaluationCache.java

License:Apache License

boolean haveConnectorCacheIntervalsLapsed(final AttributeConnectorService localConnectorService,
        final DateTime policyEvalTimestampUTC) {
    DateTime nowUTC = new DateTime().withZone(DateTimeZone.UTC);

    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;
}

From source file:com.gnuc.thoth.app.TabMain.java

License:GNU General Public License

@Override
protected void onResume() {
    super.onResume();
    if ((Minutes.minutesBetween(new DateTime(Settings.APP_LAST_SYNC_THOTH), new DateTime())).getMinutes() > 59
            && !Settings.APP_UPGRADE)
        TABMAIN.sendEmptyMessageDelayed(20, 10000);
    if (Settings.APP_SHOW_UPDATE)
        TABMAIN.sendEmptyMessageDelayed(50, 5000);
}

From source file:com.google.android.apps.paco.EsmGenerator2.java

License:Open Source License

private boolean isMinimalBufferedDistanceFromOtherTimes(DateTime plusMinutes, Minutes timeoutInMinutes) {
    for (DateTime time : times) {

        Minutes minutesBetween;/*from w  w  w  .j a v a2 s. c o  m*/
        if (time.isAfter(plusMinutes)) {
            minutesBetween = Minutes.minutesBetween(plusMinutes, time);
        } else {
            minutesBetween = Minutes.minutesBetween(time, plusMinutes);
        }

        if (minutesBetween.isLessThan(timeoutInMinutes)) {
            return false;
        }
    }
    return true;
}

From source file:com.inkubator.common.util.DateTimeUtil.java

/**
 * get total Minutes difference, between two date type
 *
 * @return Integer//from  w w  w.  j a  v  a2 s .co  m
 * @param date1 Date reference
 * @param date2 Date reference
 */
public static Integer getTotalMinutesDifference(Date date1, Date date2) {
    return Minutes.minutesBetween(new DateTime(date1), new DateTime(date2)).getMinutes();
}

From source file:com.marand.thinkmed.medications.process.impl.TherapyTaskCreatorImpl.java

License:Open Source License

private List<NewTaskRequestDto> createTasksForConstantTherapy(final long patientId,
        final MedicationInstructionInstruction instruction, final String compositionUid,
        final Interval taskCreationInterval, final TherapyDoseDto dose,
        final AdministrationTimingDto administrationTiming, final RoundsIntervalDto roundsIntervalDto,
        final boolean therapyStart, final DateTime lastTaskTimestamp, final String linkedTherapyId) {
    final DateTime therapyEnd = DataValueUtils
            .getDateTime(instruction.getOrder().get(0).getMedicationTiming().getStopDate());
    final boolean therapyEndsWithLastTask = taskCreationInterval.getEnd().equals(therapyEnd);
    final DosingFrequencyDto dosingFrequency = MedicationFromEhrConverter
            .getDosingFrequency(instruction.getOrder().get(0).getMedicationTiming());

    final List<NewTaskRequestDto> taskRequests = new ArrayList<>();

    final DateTime calculationBaseTimestamp = therapyStart ? taskCreationInterval.getStart()
            : lastTaskTimestamp;// w  w  w  . j  a  v  a2 s .  com
    if (therapyStart) {
        final NewTaskRequestDto startTaskRequest = createMedicationTaskRequest(instruction, compositionUid,
                patientId, AdministrationTypeEnum.START, taskCreationInterval.getStart(), dose);
        taskRequests.add(startTaskRequest);
    }
    if (dosingFrequency != null && dosingFrequency.getType() != DosingFrequencyTypeEnum.ONCE_THEN_EX) {
        List<HourMinuteDto> defaultAdministrationTimes = getPossibleAdministrations(administrationTiming,
                dosingFrequency.getKey());
        if (defaultAdministrationTimes == null
                && dosingFrequency.getType() == DosingFrequencyTypeEnum.DAILY_COUNT) {
            defaultAdministrationTimes = calculatePossibleAdministrationsForDailyCount(
                    dosingFrequency.getValue(), roundsIntervalDto, calculationBaseTimestamp);
        }
        final DateTime nextTime = getNextAdministrationTime(calculationBaseTimestamp,
                defaultAdministrationTimes, dosingFrequency);

        DateTime time = calculationBaseTimestamp;

        if (therapyStart && dosingFrequency.getType() != DosingFrequencyTypeEnum.BETWEEN_DOSES
                && Minutes.minutesBetween(time, nextTime).getMinutes() < 30) {
            time = getNextAdministrationTime(nextTime, defaultAdministrationTimes, dosingFrequency);
        } else {
            time = nextTime;
        }

        while (!time.isAfter(taskCreationInterval.getEnd())) {
            if (time.isAfter(taskCreationInterval.getStart())) {
                taskRequests.add(createMedicationTaskRequest(instruction, compositionUid, patientId,
                        AdministrationTypeEnum.START, time, dose));
            }
            time = getNextAdministrationTime(time, defaultAdministrationTimes, dosingFrequency);
        }
    } else if (MedicationsEhrUtils.isContinuousInfusion(instruction)) {
        if (therapyEnd != null && !therapyEnd.isAfter(taskCreationInterval.getEnd())) {
            final NewTaskRequestDto endTaskRequest = createMedicationTaskRequest(instruction, compositionUid,
                    patientId, AdministrationTypeEnum.STOP, therapyEnd, dose);
            taskRequests.add(endTaskRequest);
        }
    }

    if (therapyEndsWithLastTask) {
        final NewTaskRequestDto lastTask = taskRequests.get(taskRequests.size() - 1);
        lastTask.getVariables().add(Pair.of(MedicationTaskDef.TRIGGERS_THERAPY_ID, linkedTherapyId));
    }
    return taskRequests;
}

From source file:com.marand.thinkmed.medications.process.impl.TherapyTaskCreatorImpl.java

License:Open Source License

private List<NewTaskRequestDto> createTasksForVariableTherapy(final long patientId,
        final MedicationInstructionInstruction instruction, final String compositionUid,
        final Interval taskCreationInterval, final Map<HourMinuteDto, TherapyDoseDto> administrationTimesMap,
        final boolean therapyStart) {
    final List<NewTaskRequestDto> taskRequests = new ArrayList<>();

    Pair<DateTime, TherapyDoseDto> timeWithDose = getNextAdministrationTimeWithDose(
            therapyStart ? taskCreationInterval.getStart().minusMinutes(30) : taskCreationInterval.getStart(),
            administrationTimesMap);//  ww w.  j  a v a 2s. co  m
    if (therapyStart) {
        final NewTaskRequestDto startTaskRequest = createMedicationTaskRequest(instruction, compositionUid,
                patientId, AdministrationTypeEnum.START, taskCreationInterval.getStart(),
                timeWithDose.getSecond());
        taskRequests.add(startTaskRequest);
        if (Minutes.minutesBetween(taskCreationInterval.getStart(), timeWithDose.getFirst())
                .getMinutes() < 30) {
            timeWithDose = getNextAdministrationTimeWithDose(taskCreationInterval.getStart(),
                    administrationTimesMap);
        }
    }
    final boolean isContinuousInfusion = MedicationsEhrUtils.isContinuousInfusion(instruction);
    if (therapyStart || !isContinuousInfusion) //don't create tasks on review if continuous infusion
    {
        while (!timeWithDose.getFirst().isAfter(taskCreationInterval.getEnd())) {
            if (timeWithDose.getFirst().isAfter(taskCreationInterval.getStart())) {
                final NewTaskRequestDto medicationTaskRequest = createMedicationTaskRequest(instruction,
                        compositionUid, patientId,
                        isContinuousInfusion ? AdministrationTypeEnum.ADJUST_INFUSION
                                : AdministrationTypeEnum.START,
                        timeWithDose.getFirst(), timeWithDose.getSecond());
                taskRequests.add(medicationTaskRequest);
            }
            timeWithDose = getNextAdministrationTimeWithDose(timeWithDose.getFirst(), administrationTimesMap);

            if (MedicationsEhrUtils.isContinuousInfusion(instruction) && !timeWithDose.getFirst()
                    .withTimeAtStartOfDay().equals(taskCreationInterval.getStart().withTimeAtStartOfDay())) {
                break;
            }
        }
    }

    if (MedicationsEhrUtils.isContinuousInfusion(instruction)) {
        final DateTime therapyEnd = DataValueUtils
                .getDateTime(instruction.getOrder().get(0).getMedicationTiming().getStopDate());
        if (therapyEnd != null && !therapyEnd.isAfter(taskCreationInterval.getEnd())) {
            final NewTaskRequestDto endTaskRequest = createMedicationTaskRequest(instruction, compositionUid,
                    patientId, AdministrationTypeEnum.STOP, therapyEnd, timeWithDose.getSecond());
            taskRequests.add(endTaskRequest);
        }
    }
    return taskRequests;
}