Example usage for org.joda.time Period getYears

List of usage examples for org.joda.time Period getYears

Introduction

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

Prototype

public int getYears() 

Source Link

Document

Gets the years field part of the period.

Usage

From source file:com.squid.kraken.v4.core.analysis.engine.processor.AnalysisCompute.java

License:Open Source License

private IntervalleObject alignPastInterval(IntervalleObject presentInterval, IntervalleObject pastInterval,
        Axis joinAxis) throws ScopeException {

    if (joinAxis != null && presentInterval != null && pastInterval != null) {

        Object lowerPresent = presentInterval.getLowerBound();
        Object lowerPast = pastInterval.getLowerBound();
        Object upperPresent = presentInterval.getUpperBound();
        Object upperPast = pastInterval.getUpperBound();
        ////from   w  w w  .ja v  a2 s.c om
        IDomain image = joinAxis.getDefinition().getImageDomain();
        if (lowerPresent instanceof Date && lowerPast instanceof Date) {

            DateTime lowerPastDT = new DateTime((Date) lowerPast);
            DateTime lowerPresentDT = new DateTime((Date) lowerPresent);
            DateTime upperPresentDT = new DateTime((Date) upperPresent);
            DateTime upperPastDT = new DateTime((Date) upperPast);

            // realign
            if (image.isInstanceOf(IDomain.YEARLY)) {
                // check if present is an exact number of years
                if (lowerPresentDT.getDayOfYear() == 1
                        && upperPresentDT.getDayOfYear() == upperPresentDT.dayOfYear().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent),
                            (new LocalDate(upperPresent)), PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), (new LocalDate(upperPast)),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.years());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.years());

                        // realign
                        if (presentPeriod.getYears() > pastPeriod.getYears()) {
                            // some days are missing to align the periods
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(upperPastDT.getYear(), 1, 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }
                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over year
                                Date newUpperPast = new DateTime(upperPastDT.getYear(), 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }
                        } else {
                            // either already aligned, or some days should
                            // be removed

                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over Year
                                Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);

                            }
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                        .toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }

                        }
                    }
                }
            } else if (image.isInstanceOf(IDomain.QUATERLY) || image.isInstanceOf(IDomain.MONTHLY)) {
                // check if present is an exact number of month
                if (lowerPresentDT.getDayOfMonth() == 1
                        && upperPresentDT.getDayOfMonth() == upperPresentDT.dayOfMonth().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent), new LocalDate(upperPresent),
                            PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), new LocalDate(upperPast),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        // realign
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.months());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.months());
                        if (presentPeriod.getMonths() > pastPeriod.getMonths()) {
                            // some days are missing

                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                // month over month
                                Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                        upperPastDT.getMonthOfYear(),
                                        upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }

                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                        lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);

                            }

                        } else {
                            // either already aligned, of some days should
                            // be removed
                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                /// month over month
                                if (upperPastDT.getMonthOfYear() == 1) {
                                    Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                            .toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);

                                } else {

                                    upperPastDT = upperPastDT.minusMonths(1);
                                    Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                            upperPastDT.getMonthOfYear(),
                                            upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);
                                }
                            }
                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                if (lowerPastDT.getMonthOfYear() == 12) {
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                            .toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                } else {
                                    lowerPastDT = lowerPastDT.plusMonths(1);
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                            lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                }

                            }

                        }
                    }
                }
            }
        }
    }
    return pastInterval;
}

From source file:com.squid.kraken.v4.core.analysis.engine.processor.AnalysisCompute.java

License:Open Source License

private Period computeOffset(IntervalleObject presentInterval, IntervalleObject pastInterval,
        AxisValues joinAxis) throws ScopeException {
    // it is better to compare on the lower bound because alignment on the
    // end of month is not accurate
    Object present = presentInterval.getLowerBound();
    Object past = pastInterval.getLowerBound();
    ///*from   w  w w  . jav  a2  s  .  c  o m*/

    IDomain image = joinAxis.getAxis().getDefinition().getImageDomain();
    PeriodType type = computePeriodType(image);
    //
    if (present instanceof Date && past instanceof Date) {

        Period presentPeriod = new Period(new LocalDate(((Date) presentInterval.getLowerBound()).getTime()),
                new LocalDate(((Date) presentInterval.getUpperBound()).getTime()).plusDays(1), type);

        Period pastPeriod = new Period(new LocalDate(((Date) pastInterval.getLowerBound()).getTime()),
                new LocalDate(((Date) pastInterval.getUpperBound()).getTime()).plusDays(1), type);

        Date pastDate = (Date) past;
        DateTime dt = new DateTime(pastDate);
        if (image.isInstanceOf(IDomain.YEARLY)) {
            if (presentPeriod.getYears() > pastPeriod.getYears()) {
                // e.g. presentPeriod of 365 days ->
                // presentPeriod.getYears=1 && past year of 366 days ->
                // pastPeriod.getYears=0
                DateTime newDT = new DateTime(dt.getYear(), 1, 1, 0, 0);
                pastDate = newDT.toDate();
            } else {
                if (dt.getDayOfYear() != 1) {
                    // e.g present period of 366 days -> past date at dec 31
                    DateTime newDT = new DateTime(dt.getYear() + 1, 1, 1, 0, 0);
                    pastDate = newDT.toDate();
                }
            }
        } else if (image.isInstanceOf(IDomain.QUATERLY) || image.isInstanceOf(IDomain.MONTHLY)) {

            if (presentPeriod.getMonths() > pastPeriod.getMonths()) {
                // e.g present period of 28 days(February) ->
                // pastPeriod.getMonths() = 0 (January has 31 days)
                DateTime newDT = new DateTime(dt.getYear(), dt.getMonthOfYear(), 1, 0, 0);
                pastDate = newDT.toDate();
            } else {
                if (dt.getDayOfMonth() != 1) {
                    // e.g. present period of 31 day(March) pastDate = Feb 6
                    if (dt.getMonthOfYear() == 12) {
                        DateTime newDT = new DateTime(dt.getYear() + 1, 1, 1, 0, 0);
                        pastDate = newDT.toDate();
                    } else {
                        DateTime newDT = new DateTime(dt.getYear(), dt.getMonthOfYear() + 1, 1, 0, 0);
                        pastDate = newDT.toDate();
                    }
                }
            }
        } else {
            // daily, keep Date as it is
        }
        return new Period(new LocalDate((pastDate).getTime()), new LocalDate(((Date) present).getTime()), type);

    } else {
        return null;
    }
}

From source file:dao.ApplicationDAO.java

public static ArrayList<Application> filterByAge(int ageFrom, int ageTo, ArrayList<Application> filteredList) {
    int iAge = 0;
    ArrayList<Application> newAppList = new ArrayList<Application>();

    for (Application app : filteredList) {

        //get int dob from database
        String dateOfBirth = app.getDob();
        int dobDay = Integer.parseInt(dateOfBirth.substring(0, 2));
        int dobMonth = Integer.parseInt(dateOfBirth.substring(3, 5));
        int dobYear = Integer.parseInt(dateOfBirth.substring(6, 10));
        LocalDate dob = new LocalDate(dobYear, dobMonth, dobDay);
        LocalDate date = new LocalDate();
        Period period = new Period(dob, date, PeriodType.yearMonthDay());
        iAge = period.getYears();

        if ((iAge >= ageFrom) && (iAge <= ageTo)) {
            newAppList.add(app);//from  ww w  . j ava 2 s.  c o  m
        }
    }

    return newAppList;
}

From source file:de.azapps.mirakel.sync.taskwarrior.model.TaskWarriorTaskSerializer.java

License:Open Source License

public static void handleRecurrence(final JsonObject json, final Recurring r) {
    if (r == null) {
        Log.wtf(TAG, "recurring is null");
        return;/*from w  w w .j av a 2  s.  c om*/
    }
    if (!r.getWeekdays().isEmpty()) {
        switch (r.getWeekdays().size()) {
        case 1:
            json.addProperty("recur", "weekly");
            return;
        case 7:
            json.addProperty("recur", "daily");
            return;
        case 5:
            final List<Integer> weekdays = r.getWeekdays();
            for (Integer i = DateTimeConstants.MONDAY; i <= DateTimeConstants.FRIDAY; i++) {
                if (!weekdays.contains(i)) {
                    Log.w(TAG, "unsupported recurrence");
                    return;
                }
            }
            json.addProperty("recur", "weekdays");
            return;
        default:
            Log.w(TAG, "unsupported recurrence");
            return;
        }
    }
    final long interval = r.getIntervalMs() / (1000L * 60L);
    if (interval > 0L) {
        Period p = r.getInterval();
        if (r.getInterval().getMinutes() > 0) {
            json.addProperty("recur", p.toStandardMinutes().getMinutes() + "mins");
        } else if (r.getInterval().getHours() > 0) {
            json.addProperty("recur", p.toStandardHours().getHours() + "hours");
        } else if (r.getInterval().getDays() > 0) {
            json.addProperty("recur", p.toStandardDays().getDays() + "days");
        } else if (r.getInterval().getWeeks() > 0) {
            json.addProperty("recur", p.toStandardWeeks().getWeeks() + "weeks");
        } else if (r.getInterval().getMonths() > 0) {
            json.addProperty("recur", p.getMonths() + (12 * p.getYears()) + "months");
        } else {
            json.addProperty("recur", p.getYears() + "years");
        }
    }
}

From source file:edu.uiowa.icts.bluebutton.json.DateRange.java

License:Apache License

@JsonIgnore
public boolean isActiveIntheLastYear() {
    if (this.end == null && this.start != null) {
        DateTime now = new DateTime();
        DateTime startDateTime = PARSER_FORMAT.parseDateTime(this.start);
        Period period = new Period(startDateTime, now);
        if (period.getYears() > 0) {
            return false;
        } else {/*from   w w  w  .j  a v  a2 s .  c om*/
            return true;
        }
    } else {
        return false;
    }
}

From source file:elw.web.FormatTool.java

License:Open Source License

public String formatDuration(final long timeMillis) {
    final Period period = new Period();
    final Period periodNorm = period.plusMillis((int) Math.abs(timeMillis)).normalizedStandard();

    if (periodNorm.getYears() > 0) {
        return lookupPeriodFormatter("y").print(periodNorm);
    } else if (periodNorm.getMonths() > 0) {
        return lookupPeriodFormatter("M").print(periodNorm);
    } else if (periodNorm.getDays() > 0) {
        return lookupPeriodFormatter("d").print(periodNorm);
    } else if (periodNorm.getHours() > 0) {
        return lookupPeriodFormatter("H").print(periodNorm);
    } else if (periodNorm.getMinutes() > 0) {
        return lookupPeriodFormatter("m").print(periodNorm);
    } else {/*from  w  w w  .ja  va2s  .c  o  m*/
        //  LATER sometimes durations less than one second occur
        return lookupPeriodFormatter("s").print(periodNorm);
    }
}

From source file:GroupProject.Operation.java

/**
 * Calculates age according to the date of birth supplied as a parameter.
 *
 * @param age Date of Birth/*from w  ww.j  a v  a2 s .  c  om*/
 * @return age in years.
 */

public int calculateAge(String age) {

    final org.joda.time.format.DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/yyyy");
    final LocalDate birthdate = dtf.parseLocalDate(age);
    LocalDate now = new LocalDate(); //Today's date
    Period period = new Period(birthdate, now, PeriodType.yearMonthDay());
    int ageInYears = period.getYears();
    return ageInYears;
}

From source file:imas.inventory.sessionbean.YieldManagementSessionBean.java

@Override
public String getFlightFromNowToDepartureString(FlightEntity flight) {
    DateTime departureTime = new DateTime(flight.getDepartureDate().getTime());
    DateTime now = new DateTime();
    Period period = new Period(now, departureTime);
    int years = period.getYears();
    int months = period.getMonths();
    int days = 7 * period.getWeeks() + period.getDays();

    String res = "";
    if (years > 0) {
        if (years > 1) {
            res = res + years + " years ";
        } else {//  w  ww. j a v  a  2 s. com
            res = "1 year ";
        }
    }
    if (months > 0) {
        if (months > 1) {
            res = res + months + " months ";
        } else {
            res = res + "1 month ";
        }
    }
    if (days > 0) {
        if (days > 1) {
            res = res + days + " days";
        } else {
            res = res + "1 day";
        }
    }

    return res;
}

From source file:influent.server.utilities.DateTimeParser.java

License:MIT License

/**
 * @see http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html#normalizedStandard()
 *//*from  w  ww.j  av a  2 s .  c o  m*/
public static Period normalize(Period period) {
    long millis = period.getMillis();
    millis += period.getSeconds() * DateTimeConstants.MILLIS_PER_SECOND;
    millis += period.getMinutes() * DateTimeConstants.MILLIS_PER_MINUTE;
    millis += period.getHours() * DateTimeConstants.MILLIS_PER_HOUR;
    millis += period.getDays() * DateTimeConstants.MILLIS_PER_DAY;
    millis += period.getWeeks() * DateTimeConstants.MILLIS_PER_WEEK;

    Period result = new Period(millis, DateTimeUtils.getPeriodType(PeriodType.standard()),
            ISOChronology.getInstanceUTC());
    int years = period.getYears();
    int months = period.getMonths();

    if (years != 0 || months != 0) {
        years = FieldUtils.safeAdd(years, months / 12);
        months = months % 12;
        if (years != 0) {
            result = result.withYears(years);
        }
        if (months != 0) {
            result = result.withMonths(months);
        }
    }

    return result;
}

From source file:info.culebrasgis.calculadoradefechas.EdadActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edad);

    fechaUsuario = (Button) findViewById(R.id.buttonFechaUsuario);
    fechaUsuario.setOnClickListener(new View.OnClickListener() {
        @Override/* w  w w . ja v  a  2s  .c  o  m*/
        public void onClick(View v) {
            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });

    resultado = (TextView) findViewById(R.id.textViewResultado);

    volver = (Button) findViewById(R.id.buttonVolver);
    volver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    reiniciar = (Button) findViewById(R.id.buttonReiniciar);
    reiniciar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            resultado.setText(R.string.resultado);
            fechaUsuario.setText(R.string.fecha);
        }
    });

    calcular = (Button) findViewById(R.id.buttonCalcular);
    calcular.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                int dia, mes, anno;
                dia = Integer.parseInt(String.valueOf(fechaUsuario.getText()).substring(0, 2));
                mes = Integer.parseInt(String.valueOf(fechaUsuario.getText()).substring(3, 5));
                anno = Integer.parseInt(String.valueOf(fechaUsuario.getText()).substring(6, 10));

                DateTime hoy = new DateTime();
                DateTime fecha = new DateTime(anno, mes, dia, 0, 0);

                if (fecha.isAfter(hoy)) { // si el usuario mete una fecha posterior al da actual
                    resultado.setText(R.string.nacer_futuro);
                } else {
                    Period periodo = new Period(fecha, hoy, PeriodType.yearMonthDay());
                    resultado.setText(String.format(getString(R.string.resultado_edad), periodo.getYears(),
                            periodo.getMonths(), periodo.getDays()));
                }
            } catch (Exception e) {
                resultado.setText(R.string.fecha_incorrecta);
            }
        }
    });

}