Example usage for org.joda.time Period getMonths

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

Introduction

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

Prototype

public int getMonths() 

Source Link

Document

Gets the months field part of the period.

Usage

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;//  w  ww . j  a  va2  s  .c o  m
    }
    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: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 {//www.  ja v a2 s . co  m
        //  LATER sometimes durations less than one second occur
        return lookupPeriodFormatter("s").print(periodNorm);
    }
}

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 {/*from w w w.j a va  2 s  .  co  m*/
            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  w w  .j a v 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 ww.java2 s .  co  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);
            }
        }
    });

}

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

License:Open Source License

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

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

    fechaUsuario2 = (Button) findViewById(R.id.buttonFechaUsuario2);
    fechaUsuario2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment newFragment = new DatePickerFragment2();
            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);
            fechaUsuario2.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, dia2, mes2, anno2;
                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));

                dia2 = Integer.parseInt(String.valueOf(fechaUsuario2.getText()).substring(0, 2));
                mes2 = Integer.parseInt(String.valueOf(fechaUsuario2.getText()).substring(3, 5));
                anno2 = Integer.parseInt(String.valueOf(fechaUsuario2.getText()).substring(6, 10));

                DateTime fecha = new DateTime(anno, mes, dia, 0, 0);
                DateTime fecha2 = new DateTime(anno2, mes2, dia2, 0, 0);

                Period periodo;

                if (fecha.isBefore(fecha2)) { // si la primera fecha es anterior
                    periodo = new Period(fecha, fecha2, PeriodType.yearMonthDay());
                } else { // si la que es anterior es la segunda fecha
                    periodo = new Period(fecha2, fecha, PeriodType.yearMonthDay());
                }

                resultado.setText(String.format(getString(R.string.resultado_intervalo), periodo.getYears(),
                        periodo.getMonths(), periodo.getDays()));

            } catch (Exception e) {
                resultado.setText(R.string.fechas_incorrectas);
            }
        }
    });

}

From source file:io.coala.xml.XmlUtil.java

License:Apache License

/**
 * @param period/*from w w  w.j a v a2  s  .c  om*/
 * @return a JAXP {@link Duration}
 */
public static Duration toDuration(final Period period) {
    return getDatatypeFactory().newDuration(true, period.getYears(), period.getMonths(), period.getDays(),
            period.getHours(), period.getMinutes(), period.getSeconds());
}

From source file:io.druid.sql.calcite.expression.builtin.TimeFloorOperatorConversion.java

License:Apache License

private static boolean periodIsDayMultiple(final Period period) {
    return period.getMillis() == 0 && period.getSeconds() == 0 && period.getMinutes() == 0
            && period.getHours() == 0 && (period.getDays() > 0 || period.getWeeks() > 0
                    || period.getMonths() > 0 || period.getYears() > 0);
}

From source file:io.konig.dao.core.ChartWriterFactory.java

License:Apache License

private Formatter categoryFormatter(Chart chart) {

    ChartCategories categories = chart.getCategories();
    if (categories instanceof DateTimeCategories) {
        String pattern = null;//from  w w w  . ja v a2s . c  om
        DateTimeCategories c = (DateTimeCategories) categories;
        Period period = c.getInterval();

        if (period.getHours() > 0) {
            pattern = HOUR;
        } else if (period.getDays() > 0) {
            pattern = DATE;
        } else if (period.getMonths() > 0) {
            pattern = MONTH;
        } else if (period.getYears() > 0) {
            pattern = YEAR;
        } else {
            throw new RuntimeException("Unsupported period: " + period.toString());
        }
        return new TemporalFormatter(DateTimeFormat.forPattern(pattern));
    }
    if (categories instanceof LabelCategories) {
        return new Formatter() {
            @Override
            public String format(Object value) {
                return (String) value;
            }
        };
    }
    // TODO: support other categories
    throw new RuntimeException("Category type not supported");

}

From source file:io.warp10.script.functions.DURATION.java

License:Apache License

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    Object o = stack.pop();/*  w  w w  .  j  a v a  2  s  . co  m*/

    if (!(o instanceof String)) {
        throw new WarpScriptException(getName()
                + " expects an ISO8601 duration (a string) on top of the stack. See http://en.wikipedia.org/wiki/ISO_8601#Durations");
    }

    ReadWritablePeriod period = new MutablePeriod();

    ISOPeriodFormat.standard().getParser().parseInto(period, o.toString(), 0, Locale.US);

    Period p = period.toPeriod();

    if (p.getMonths() != 0 || p.getYears() != 0) {
        throw new WarpScriptException(getName()
                + " doesn't support ambiguous durations containing years or months, please convert those to days.");
    }

    Duration duration = p.toDurationFrom(new Instant());

    stack.push(duration.getMillis() * Constants.TIME_UNITS_PER_MS);

    return stack;
}