Example usage for org.joda.time DateMidnight DateMidnight

List of usage examples for org.joda.time DateMidnight DateMidnight

Introduction

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

Prototype

public DateMidnight(Object instant) 

Source Link

Document

Constructs an instance from an Object that represents a datetime.

Usage

From source file:org.key2gym.client.util.DateMidnightToStringConverter.java

License:Apache License

@Override
public DateMidnight convertReverse(String value) {
    value = value.trim();//w ww .  ja v  a  2  s .c om
    if (value.isEmpty())
        return null;

    try {
        return new DateMidnight(new SimpleDateFormat(format).parse(value));
    } catch (ParseException ex) {
        throw new IllegalArgumentException(new ValidationException(
                MessageFormat.format(strings.getString("Message.FieldIsNotFilledInCorrectly.withFieldName"),
                        new Object[] { fieldName })));
    }
}

From source file:org.kuali.kpme.tklm.time.detail.validation.TimeDetailValidationUtil.java

License:Educational Community License

public static List<String> validateOverlap(Long startTime, Long endTime, boolean acrossDays, String startDateS,
        String endTimeS, DateTime startTemp, DateTime endTemp, TimesheetDocument timesheetDocument,
        String timeblockId, boolean isRegularEarnCode) {
    List<String> errors = new ArrayList<String>();
    Interval addedTimeblockInterval = new Interval(startTime, endTime);
    List<Interval> dayInt = new ArrayList<Interval>();

    //if the user is clocked in, check if this time block overlaps with the clock action
    ClockLog lastClockLog = TkServiceLocator.getClockLogService()
            .getLastClockLog(HrContext.getTargetPrincipalId());
    if (lastClockLog != null && (lastClockLog.getClockAction().equals(TkConstants.CLOCK_IN)
            || lastClockLog.getClockAction().equals(TkConstants.LUNCH_IN))) {
        DateTime lastClockDateTime = lastClockLog.getClockDateTime();
        String lastClockZone = lastClockLog.getClockTimestampTimezone();
        if (StringUtils.isEmpty(lastClockZone)) {
            lastClockZone = TKUtils.getSystemTimeZone();
        }//from   ww w . ja va  2s .  c  o  m
        DateTimeZone zone = DateTimeZone.forID(lastClockZone);
        DateTime clockWithZone = lastClockDateTime.withZone(zone);
        DateTime currentTime = new DateTime(System.currentTimeMillis(), zone);
        Interval currentClockInInterval = new Interval(clockWithZone.getMillis(), currentTime.getMillis());

        if (isRegularEarnCode && addedTimeblockInterval.overlaps(currentClockInInterval)) {
            errors.add("The time block you are trying to add overlaps with the current clock action.");
            return errors;
        }
    }

    if (acrossDays) {
        DateTime start = new DateTime(startTime);
        DateTime end = TKUtils.convertDateStringToDateTime(startDateS, endTimeS);
        if (endTemp.getDayOfYear() - startTemp.getDayOfYear() < 1) {
            end = new DateTime(endTime);
        }
        DateTime groupEnd = new DateTime(endTime);
        Long startLong = start.getMillis();
        Long endLong = end.getMillis();
        //create interval span if start is before the end and the end is after the start except
        //for when the end is midnight ..that converts to midnight of next day
        DateMidnight midNight = new DateMidnight(endLong);
        while (start.isBefore(groupEnd.getMillis()) && ((endLong >= startLong) || end.isEqual(midNight))) {
            Interval tempInt = null;
            if (end.isEqual(midNight)) {
                tempInt = addedTimeblockInterval;
            } else {
                tempInt = new Interval(startLong, endLong);
            }
            dayInt.add(tempInt);
            start = start.plusDays(1);
            end = end.plusDays(1);
            startLong = start.getMillis();
            endLong = end.getMillis();
        }
    } else {
        dayInt.add(addedTimeblockInterval);
    }

    for (TimeBlock timeBlock : timesheetDocument.getTimeBlocks()) {
        if (errors.size() == 0 && StringUtils.equals(timeBlock.getEarnCodeType(), HrConstants.EARN_CODE_TIME)) {
            Interval timeBlockInterval = new Interval(timeBlock.getBeginTimestamp().getTime(),
                    timeBlock.getEndTimestamp().getTime());
            for (Interval intv : dayInt) {
                if (isRegularEarnCode && timeBlockInterval.overlaps(intv)
                        && (timeblockId == null || timeblockId.compareTo(timeBlock.getTkTimeBlockId()) != 0)) {
                    errors.add("The time block you are trying to add overlaps with an existing time block.");
                }
            }
        }
    }

    return errors;
}

From source file:org.kuali.student.enrollment.class2.acal.service.impl.AcademicCalendarViewHelperServiceImpl.java

License:Educational Community License

/**
 * Calculate and returns the valid number of final exam period days based on the excludeSaturday/excludeSunday setting.
 * Also, overlapping non-instructional holidays will be subtracted as well.
 *
 * @param examPeriodWrapper exam period wrapper
 * @param holidayInfos list of holidayinfos of the academic calendar
 *///www  . jav a2  s  .  c  o m
protected int getDaysForExamPeriod(ExamPeriodWrapper examPeriodWrapper, List<HolidayInfo> holidayInfos,
        ContextInfo contextInfo) throws Exception {
    //trap null parameters
    if (examPeriodWrapper == null) {
        throw new Exception("Exam Period wrapper is null");
    }

    int examPeriodDays = 0;
    boolean excludeSaturday = examPeriodWrapper.isExcludeSaturday();
    boolean excludeSunday = examPeriodWrapper.isExcludeSunday();

    DateMidnight currentDateExamPeriod = new DateMidnight(examPeriodWrapper.getStartDate().getTime());
    DateMidnight endDateExamPeriod = new DateMidnight(examPeriodWrapper.getEndDate().getTime());

    // go from start to end and count exam period days
    while (currentDateExamPeriod.compareTo(endDateExamPeriod) <= 0) {
        // if it is Saturday or Sunday and the exam period set exclude Saturday or Sunday attr
        // do not count that day
        if (!(((currentDateExamPeriod.getDayOfWeek() == DateTimeConstants.SATURDAY) && excludeSaturday)
                || ((currentDateExamPeriod.getDayOfWeek() == DateTimeConstants.SUNDAY) && excludeSunday))) {
            ++examPeriodDays;
        }

        currentDateExamPeriod = currentDateExamPeriod.plusDays(1);
    }

    //if there is a holiday calendar for the academic calendar where the exam period is in,
    //check if there are holidays overlapping with the exam period
    if (holidayInfos != null && !holidayInfos.isEmpty()) {
        List<DateMidnight> holidayDatesToSubtract = new ArrayList<DateMidnight>();
        for (HolidayInfo holidayInfo : holidayInfos) {
            Boolean isInstDay = holidayInfo.getIsInstructionalDay();
            Boolean isDateRange = holidayInfo.getIsDateRange();
            Date holStartDate = holidayInfo.getStartDate();
            Date holEndDate = holidayInfo.getEndDate();

            // If's it's not a range then the start and end dates are the same
            if (!isDateRange) {
                holEndDate = holStartDate;
            }

            // if holiday is an instructional day, it doesn't need to be subtracted from the exam period
            if (!isInstDay) {
                DateMidnight currentDate = new DateMidnight(holStartDate.getTime());
                DateMidnight stopDate = new DateMidnight(holEndDate.getTime());
                while (currentDate.compareTo(stopDate) <= 0) {
                    if (doDatesOverlap(examPeriodWrapper.getStartDate(), examPeriodWrapper.getEndDate(),
                            currentDate.toDate(), currentDate.toDate())) {
                        //if holiday is on Saturday or Sunday and excludeSaturday/excludeSunday is set,
                        //the holiday doesn't need to be subtracted again because the Saturday/Sunday has already been excluded
                        if (!(((currentDate.getDayOfWeek() == DateTimeConstants.SATURDAY) && excludeSaturday)
                                || ((currentDate.getDayOfWeek() == DateTimeConstants.SUNDAY)
                                        && excludeSunday))) {
                            if (!holidayDatesToSubtract.contains(currentDate)) {
                                holidayDatesToSubtract.add(currentDate);
                                --examPeriodDays;
                            }
                        }
                    }
                    currentDate = currentDate.plusDays(1);
                }
            }
        }
    }

    return examPeriodDays;
}

From source file:org.mifos.application.importexport.xls.XlsClientsImporter.java

License:Open Source License

private void validateAge(final Date dateOfBirth) throws CellException, ConfigurationException {
    final DateMidnight dob = new DateMidnight(dateOfBirth);
    final DateTime now = new DateTime();
    final Years age = Years.yearsBetween(dob, now);

    final int minimumAge = ClientRules.getMinimumAge();
    final int maximumAge = ClientRules.getMaximumAge();

    if (age.getYears() < 0) {
        throw new CellException(getMessage(XlsMessageConstants.FUTURE_DATE));
    } else if (ClientRules.isAgeCheckEnabled() && !ClientRules.isAgeCheckWarningInsteadOfErrorEnabled()
            && (age.getYears() < minimumAge || age.getYears() > maximumAge)) {
        throw new CellException(
                getMessage(XlsMessageConstants.INVALID_AGE, new Object[] { minimumAge, maximumAge }));
    }/*from   w w w . j  a  va  2 s.  c  o  m*/
}

From source file:org.mifos.ui.core.controller.HolidayFormValidator.java

License:Open Source License

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = {
        "REC_CATCH_EXCEPTION" }, justification = "Using catch all to detect invalid dates.")
@SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NPathComplexity" })
@Override/*w  w w.  j  ava 2  s  . c  om*/
public void validate(Object target, Errors errors) {

    if (target instanceof OfficeHoliday) {
        return;
    }

    HolidayFormBean formBean = (HolidayFormBean) target;
    rejectIfEmptyOrWhitespace(errors, formBean.getName(), "error.holiday.mandatory_field");

    Date dateFrom = null;
    Date dateTo = null;
    try {
        dateFrom = new DateTime().withDate(Integer.parseInt(formBean.getFromYear()), formBean.getFromMonth(),
                formBean.getFromDay()).toDate();
    } catch (Exception e) {
        errors.reject("holiday.fromDate.invalid");
    }

    if (formBean.anyToDateFieldFilled() && !formBean.allToDateFieldsFilled()) {
        errors.reject("holiday.thruDate.invalid");
    }

    try {
        if (formBean.getToDay() != null) {
            dateTo = new DateTime().withDate(Integer.parseInt(formBean.getToYear()), formBean.getToMonth(),
                    formBean.getToDay()).toDate();
        }
    } catch (Exception e) {
        if (!errors.hasFieldErrors("holiday.thruDate.invalid")) {
            errors.reject("holiday.thruDate.invalid");
        }
    }

    // FIXME - keithw - the follow validation performed below is really business logic validation and not web-data-validation
    // it should exist in one place within the domain layer
    if (dateFrom != null && dateTo != null && new DateTime(dateFrom).compareTo(new DateTime(dateTo)) > 0) {
        errors.reject("holiday.fromDate.invalid2");
    }

    if (dateFrom != null && new DateMidnight(dateFrom).compareTo(new DateMidnight()) < 0) {
        errors.reject("holiday.fromDate.invalid3");
    }

    if (dateFrom != null && new DateMidnight(dateFrom).compareTo(new DateMidnight()) == 0) {
        errors.reject("holiday.fromDate.invalid4");
    }
    // end of business logic rules

    if (formBean.getRepaymentRuleId() == null || Integer.parseInt(formBean.getRepaymentRuleId()) < 0) {
        errors.reject("holiday.repaymentrule.required");
    }

    if (formBean.getSelectedOfficeIds().trim().isEmpty()) {
        errors.reject("holiday.appliesto.required");
    }
}

From source file:org.openmrs.module.emrapi.encounter.EncounterDomainWrapper.java

License:Open Source License

/**
 * Associates the encounter with the specified visit
 * If the encounterDatetime has only a Date component, adds a time component (if necessary) based on our business logic:
 * if this is an open visit and encounter date = today, consider a real-tiome transaction and we stamp with the current time,
 * otherwise we add a time component (if necessary) to make sure the encounter falls within the specified visit
 *
 * @param visit//from   w  w w.  j a  v a  2  s .c  o m
 * @throws EncounterDateBeforeVisitStartDateException
 *
 * @throws EncounterDateAfterVisitStopDateException
 *
 */
@Transactional
public void attachToVisit(VisitDomainWrapper visit)
        throws EncounterDateBeforeVisitStartDateException, EncounterDateAfterVisitStopDateException {

    // if time component already exists, for now we just verify that the encounter falls within the visit
    if (dateHasTimeComponent(encounter.getEncounterDatetime())) {

        if (encounter.getEncounterDatetime().before(visit.getStartDatetime())) {
            throw new EncounterDateBeforeVisitStartDateException();
        }

        if (visit.getStopDatetime() != null
                && encounter.getEncounterDatetime().after(visit.getStopDatetime())) {
            throw new EncounterDateAfterVisitStopDateException();
        }

    }
    // otherwise, properly set the time component
    else {

        DateMidnight encounterDate = new DateMidnight(encounter.getEncounterDatetime());
        DateMidnight currentDate = new DateMidnight();
        DateMidnight visitStartDate = new DateMidnight(visit.getStartDatetime());
        DateMidnight visitStopDate = visit.getStopDatetime() != null ? new DateMidnight(visit.getStopDatetime())
                : null;

        if (encounterDate.isBefore(visitStartDate)) {
            throw new EncounterDateBeforeVisitStartDateException();
        }

        if (visitStopDate != null && encounterDate.isAfter(visitStopDate)) {
            throw new EncounterDateAfterVisitStopDateException();
        }

        // if encounter date = today and open visit, consider this a real-time transaction and timestamp with current datetime
        if (encounterDate.equals(currentDate) && visit.isOpen()) {
            setEncounterDatetimeAndPropagateToObs(encounter, new Date());
        }

        // otherwise, consider a retrospective encounter, and so we want an encounter date to have no time component, EXCEPT
        // if this encounter is on the first day of the visit, the encounter datetime cannot be before the visit start time
        else if (encounterDate.isBefore(new DateTime(visit.getStartDatetime()))) {
            setEncounterDatetimeAndPropagateToObs(encounter, visit.getStartDatetime());
        }

        // otherwise, leave encounter date as is
    }

    // now associate with the visit
    encounter.setVisit(visit.getVisit());
}

From source file:org.openmrs.module.emrapi.encounter.EncounterDomainWrapper.java

License:Open Source License

private boolean dateHasTimeComponent(Date date) {
    return !new DateTime(date).equals(new DateMidnight(date));
}

From source file:org.openmrs.module.emrapi.visit.VisitDomainWrapper.java

License:Open Source License

public Date getStartDate() {
    return visit.getStartDatetime() != null ? new DateMidnight(visit.getStartDatetime()).toDate() : null;
}

From source file:org.openmrs.module.emrapi.visit.VisitDomainWrapper.java

License:Open Source License

public Date getStopDate() {
    return visit.getStopDatetime() != null ? new DateMidnight(visit.getStopDatetime()).toDate() : null;
}

From source file:org.openmrs.module.htmlformentryui.fragment.controller.htmlform.EnterHtmlFormFragmentController.java

License:Open Source License

private boolean hasNoTimeComponent(Date date) {
    return new DateMidnight(date).toDate().equals(date);
}