Example usage for org.joda.time Period get

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

Introduction

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

Prototype

public int get(DurationFieldType type) 

Source Link

Document

Gets the value of one of the fields.

Usage

From source file:com.facebook.util.TimeIntervalType.java

License:Apache License

/**
 * Gets the start instant given the event instant, interval length 
 * and the time zone for this interval type.
 * /*from w  w  w .  j a v a2s. co m*/
 * @param instant the event time instant.
 * @param length the interval length
 * 
 * @return the start instant of the interval of given length that contains 
 * the supplied time instant in the supplied time zone 
 */
public DateTime getTimeIntervalStart(DateTime instant, long length) {
    validateValue(instant.getZone(), length);
    // Get the time in the specified timezone
    DateTime periodStart = instant;
    // Clear all the fields for this intervalType and its subtypes
    TimeIntervalType timeIntervalType = this;
    while (timeIntervalType != null) {
        periodStart = timeIntervalType.clearField(periodStart);
        timeIntervalType = timeIntervalType.subType;
    }
    // figure out the which time interval does the instant lie in
    Period period = new Period(periodStart, instant, periodType);
    DurationField durationField = fieldType.getField(instant.getChronology()).getDurationField();
    int diff = period.get(durationField.getType());
    long startDelta = (diff / length) * length;
    return periodStart.withFieldAdded(durationField.getType(), FieldUtils.safeToInt(startDelta));
}

From source file:com.none.tom.simplerssreader.utils.DateUtils.java

License:Open Source License

public static String parseDate(final Context context, final Date date) {
    final Period period = new Period(new DateTime(date).getMillis(), System.currentTimeMillis());

    final int[] plurals = { R.plurals.years, R.plurals.months, R.plurals.weeks, R.plurals.days, R.plurals.hours,
            R.plurals.minutes, R.plurals.less_than_minutes };

    final DurationFieldType[] durationTypes = { DurationFieldType.years(), DurationFieldType.months(),
            DurationFieldType.weeks(), DurationFieldType.days(), DurationFieldType.hours(),
            DurationFieldType.minutes() };

    final Resources res = context.getResources();

    for (int i = 0; i < durationTypes.length; i++) {
        final int value = period.get(durationTypes[i]);

        if (value > 0) {
            return value + res.getQuantityString(plurals[i], value);
        }/*from   w w  w  . j  a  v  a2 s.  co  m*/
    }

    return res.getQuantityString(plurals[plurals.length - 1], 1);
}

From source file:io.prestosql.util.DateTimeUtils.java

License:Apache License

private static Period parsePeriod(PeriodFormatter periodFormatter, String value) {
    boolean negative = value.startsWith("-");
    if (negative) {
        value = value.substring(1);//from  ww  w .  ja v a  2  s.com
    }

    Period period = periodFormatter.parsePeriod(value);
    for (DurationFieldType type : period.getFieldTypes()) {
        checkArgument(period.get(type) >= 0, "Period field %s is negative", type);
    }

    if (negative) {
        period = period.negated();
    }
    return period;
}

From source file:org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.date.BeamSqlTimestampMinusTimestampExpression.java

License:Apache License

private long numberOfIntervalsBetweenDates(DateTime timestampStart, DateTime timestampEnd) {
    Period period = new Period(timestampStart, timestampEnd,
            PeriodType.forFields(new DurationFieldType[] { durationFieldType(intervalType) }));
    return period.get(durationFieldType(intervalType));
}

From source file:org.fenixedu.idcards.ui.candidacydocfiller.SantanderPdfFiller.java

License:Open Source License

private ByteArrayOutputStream getFilledPdfSantanderApplication(Person person)
        throws IOException, DocumentException {
    InputStream istream = getClass().getResourceAsStream(SANTANDER_APPLICATION_PDF_PATH);
    PdfReader reader = new PdfReader(istream);
    reader.getAcroForm().remove(PdfName.SIGFLAGS);
    reader.selectPages("1,2");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, output);
    form = stamper.getAcroFields();/*www.ja va  2 s  .  c  om*/

    setField("topmostSubform[0].Page1[0].Nomecompleto[0]", person.getName());
    String documentIdNumber = person.getDocumentIdNumber();
    if (person.getIdDocumentType().equals(IDDocumentType.CITIZEN_CARD)
            || person.getIdDocumentType().equals(IDDocumentType.IDENTITY_CARD)) {
        setField("topmostSubform[0].Page1[0].NumBICartaoCidadaooutro[0]", documentIdNumber);
        setField("topmostSubform[0].Page1[0].Checkdigit[0]",
                person.getIdentificationDocumentSeriesNumberValue());
    } else {
        setField("topmostSubform[0].Page1[0].Outrotipodocidentificacao[0]", documentIdNumber);
    }

    YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
    if (emissionDate != null) {
        setField("topmostSubform[0].Page1[0].Dataemissao[0]",
                emissionDate.toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    }
    setField("topmostSubform[0].Page1[0].Datavalidade[0]", person.getExpirationDateOfDocumentIdYearMonthDay()
            .toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    setField("topmostSubform[0].Page1[0].NIF[0]", person.getSocialSecurityNumber());
    setField("topmostSubform[0].Page1[0].Datanascimento[0]",
            person.getDateOfBirthYearMonthDay().toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    YearMonthDay dateOfBirthYearMonthDay = person.getDateOfBirthYearMonthDay();
    Period periodBetween = new Period(dateOfBirthYearMonthDay, new YearMonthDay());
    setField("topmostSubform[0].Page1[0].Idadeactual[0]",
            String.valueOf(periodBetween.get(DurationFieldType.years())));
    if (person.isFemale()) {
        setField("topmostSubform[0].Page1[0].Sexo[0]", "F"); // female
    } else if (person.isMale()) {
        setField("topmostSubform[0].Page1[0].Sexo[0]", "M"); // male
    }

    switch (person.getMaritalStatus()) {
    case CIVIL_UNION:
        setField("topmostSubform[0].Page1[0].Uniaofacto[0]", "1");
        break;
    case DIVORCED:
        setField("topmostSubform[0].Page1[0].Divorciado[0]", "1");
        break;
    case MARRIED:
        setField("topmostSubform[0].Page1[0].Casado[0]", "1");
        break;
    case SEPARATED:
        setField("topmostSubform[0].Page1[0].Separado[0]", "1");
        break;
    case SINGLE:
        setField("topmostSubform[0].Page1[0].Solteiro[0]", "1");
        break;
    case WIDOWER:
        setField("topmostSubform[0].Page1[0].Viuvo[0]", "1");
        break;
    }
    setField("topmostSubform[0].Page1[0].Telemovel[0]", person.getDefaultMobilePhoneNumber());
    setField("topmostSubform[0].Page1[0].E-mail[0]", getMail(person));

    setField("topmostSubform[0].Page1[0].Moradaresidenciapermanente[0]", person.getAddress());
    setField("topmostSubform[0].Page1[0].localidade[0]", person.getAreaOfAreaCode());
    String postalCode = person.getPostalCode();
    int dashIndex = postalCode.indexOf('-');
    setField("topmostSubform[0].Page1[0].CodPostal[0]", postalCode.substring(0, 4));
    String last3Numbers = person.getPostalCode().substring(dashIndex + 1, dashIndex + 4);
    setField("topmostSubform[0].Page1[0].ExtensaoCodPostal[0]", last3Numbers);

    setField("topmostSubform[0].Page1[0].Paisnacionalidade",
            person.getCountry().getCountryNationality().getPreferedContent());
    setField("topmostSubform[0].Page1[0].Paisnascimento", person.getCountryOfBirth().getName());
    setField("topmostSubform[0].Page1[0].Paisresidencia", person.getCountryOfResidence().getName());

    setField("topmostSubform[0].Page2[0].InstituioEnsinoSuperior[0]",
            UniversityUnit.getInstitutionsUniversityUnit().getName());
    setField("topmostSubform[0].Page2[0].FaculdadeEscola[0]",
            Bennu.getInstance().getInstitutionUnit().getName());
    Registration registration = getRegistration(person);
    if (registration != null) {
        setField("topmostSubform[0].Page2[0].Curso[0]", registration.getDegree().getSigla());
        setField("topmostSubform[0].Page2[0].AnoIncioCurso[0]",
                String.valueOf(registration.getStartDate().getYear()));
    }

    stamper.setFormFlattening(true);
    stamper.close();
    return output;
}

From source file:org.gephi.desktop.timeline.DateTick.java

License:Open Source License

public static DateTick create(double min, double max, int width) {

    DateTime minDate = new DateTime((long) min);
    DateTime maxDate = new DateTime((long) max);

    Period period = new Period(minDate, maxDate, PeriodType.yearMonthDayTime());
    ;/*from  ww  w . j  a  va 2s .c  o  m*/
    int years = period.getYears();
    int months = period.getMonths();
    int days = period.getDays();
    int hours = period.getHours();
    int minutes = period.getMinutes();
    int seconds = period.getSeconds();

    //Top type
    DateTimeFieldType topType;
    if (years > 0) {
        topType = DateTimeFieldType.year();
    } else if (months > 0) {
        topType = DateTimeFieldType.monthOfYear();
    } else if (days > 0) {
        topType = DateTimeFieldType.dayOfMonth();
    } else if (hours > 0) {
        topType = DateTimeFieldType.hourOfDay();
    } else if (minutes > 0) {
        topType = DateTimeFieldType.minuteOfHour();
    } else if (seconds > 0) {
        topType = DateTimeFieldType.secondOfMinute();
    } else {
        topType = DateTimeFieldType.millisOfSecond();
    }

    //Bottom type
    if (topType != DateTimeFieldType.millisOfSecond()) {
        DateTimeFieldType bottomType;
        if (topType.equals(DateTimeFieldType.year())) {
            bottomType = DateTimeFieldType.monthOfYear();
        } else if (topType.equals(DateTimeFieldType.monthOfYear())) {
            bottomType = DateTimeFieldType.dayOfMonth();
        } else if (topType.equals(DateTimeFieldType.dayOfMonth())) {
            bottomType = DateTimeFieldType.hourOfDay();
        } else if (topType.equals(DateTimeFieldType.hourOfDay())) {
            bottomType = DateTimeFieldType.minuteOfHour();
        } else if (topType.equals(DateTimeFieldType.minuteOfHour())) {
            bottomType = DateTimeFieldType.secondOfMinute();
        } else {
            bottomType = DateTimeFieldType.millisOfSecond();
        }

        //Number of ticks
        Period p = new Period(minDate, maxDate,
                PeriodType.forFields(new DurationFieldType[] { bottomType.getDurationType() }));
        int intervals = p.get(bottomType.getDurationType());
        if (intervals > 0) {
            int intervalSize = width / intervals;
            if (intervalSize >= MIN_PIXELS) {
                return new DateTick(minDate, maxDate, new DateTimeFieldType[] { topType, bottomType });
            }
        }
    }

    return new DateTick(minDate, maxDate, new DateTimeFieldType[] { topType });
}

From source file:org.graylog2.indexer.rotation.strategies.TimeBasedRotationStrategy.java

License:Open Source License

/**
 * Determines the starting point ("anchor") for a period.
 *
 * To produce repeatable rotation points in time, the period is "snapped" to a "grid" of time.
 * For example, an hourly index rotation would be anchored to the last full hour, instead of happening at whatever minute
 * the first rotation was started.//from  ww  w  .ja v  a2  s  . c o m
 *
 * This "snapping" is done accordingly with the other parts of a period.
 *
 * For highly irregular periods (those that do not have a small zero component)
 *
 * @param period the rotation period
 * @return the anchor DateTime to calculate rotation periods from
 */
protected static DateTime determineRotationPeriodAnchor(@Nullable DateTime lastAnchor, Period period) {
    final Period normalized = period.normalizedStandard();
    int years = normalized.getYears();
    int months = normalized.getMonths();
    int weeks = normalized.getWeeks();
    int days = normalized.getDays();
    int hours = normalized.getHours();
    int minutes = normalized.getMinutes();
    int seconds = normalized.getSeconds();

    if (years == 0 && months == 0 && weeks == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
        throw new IllegalArgumentException("Invalid rotation period specified");
    }

    // find the largest non-zero stride in the period. that's our anchor type. statement order matters here!
    DateTimeFieldType largestStrideType = null;
    if (seconds > 0)
        largestStrideType = secondOfMinute();
    if (minutes > 0)
        largestStrideType = minuteOfHour();
    if (hours > 0)
        largestStrideType = hourOfDay();
    if (days > 0)
        largestStrideType = dayOfMonth();
    if (weeks > 0)
        largestStrideType = weekOfWeekyear();
    if (months > 0)
        largestStrideType = monthOfYear();
    if (years > 0)
        largestStrideType = year();
    if (largestStrideType == null) {
        throw new IllegalArgumentException("Could not determine rotation stride length.");
    }

    final DateTime anchorTime = MoreObjects.firstNonNull(lastAnchor, Tools.nowUTC());

    final DateTimeField field = largestStrideType.getField(anchorTime.getChronology());
    // use normalized here to make sure we actually have the largestStride type available! see https://github.com/Graylog2/graylog2-server/issues/836
    int periodValue = normalized.get(largestStrideType.getDurationType());
    final long fieldValue = field.roundFloor(anchorTime.getMillis());

    final int fieldValueInUnit = field.get(fieldValue);
    if (periodValue == 0) {
        // https://github.com/Graylog2/graylog2-server/issues/836
        log.warn(
                "Determining stride length failed because of a 0 period. Defaulting back to 1 period to avoid crashing, but this is a bug!");
        periodValue = 1;
    }
    final long difference = (fieldValueInUnit % periodValue);
    final long newValue = field.add(fieldValue, -1 * difference);
    return new DateTime(newValue, DateTimeZone.UTC);
}

From source file:org.graylog2.indexer.rotation.TimeBasedRotationStrategy.java

License:Open Source License

/**
 * Determines the starting point ("anchor") for a period.
 *
 * To produce repeatable rotation points in time, the period is "snapped" to a "grid" of time.
 * For example, an hourly index rotation would be anchored to the last full hour, instead of happening at whatever minute
 * the first rotation was started.//from ww  w .  j  a  v  a  2  s  .c  om
 *
 * This "snapping" is done accordingly with the other parts of a period.
 *
 * For highly irregular periods (those that do not have a small zero component)
 *
 * @param period the rotation period
 * @return the anchor DateTime to calculate rotation periods from
 */
protected static DateTime determineRotationPeriodAnchor(Period period) {
    final Period normalized = period.normalizedStandard();
    int years = normalized.getYears();
    int months = normalized.getMonths();
    int weeks = normalized.getWeeks();
    int days = normalized.getDays();
    int hours = normalized.getHours();
    int minutes = normalized.getMinutes();
    int seconds = normalized.getSeconds();

    if (years == 0 && months == 0 && weeks == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
        throw new IllegalArgumentException("Invalid rotation period specified");
    }

    // find the largest non-zero stride in the period. that's our anchor type. statement order matters here!
    DateTimeFieldType largestStrideType = null;
    if (seconds > 0)
        largestStrideType = secondOfMinute();
    if (minutes > 0)
        largestStrideType = minuteOfHour();
    if (hours > 0)
        largestStrideType = hourOfDay();
    if (days > 0)
        largestStrideType = dayOfMonth();
    if (weeks > 0)
        largestStrideType = weekOfWeekyear();
    if (months > 0)
        largestStrideType = monthOfYear();
    if (years > 0)
        largestStrideType = year();
    if (largestStrideType == null) {
        throw new IllegalArgumentException("Could not determine rotation stride length.");
    }

    final DateTime now = Tools.iso8601();

    final DateTimeField field = largestStrideType.getField(now.getChronology());
    // use normalized here to make sure we actually have the largestStride type available! see https://github.com/Graylog2/graylog2-server/issues/836
    int periodValue = normalized.get(largestStrideType.getDurationType());
    final long fieldValue = field.roundFloor(now.getMillis());

    final int fieldValueInUnit = field.get(fieldValue);
    if (periodValue == 0) {
        // https://github.com/Graylog2/graylog2-server/issues/836
        log.warn(
                "Determining stride length failed because of a 0 period. Defaulting back to 1 period to avoid crashing, but this is a bug!");
        periodValue = 1;
    }
    final long difference = (fieldValueInUnit % periodValue);
    final long newValue = field.add(fieldValue, -1 * difference);
    return new DateTime(newValue, DateTimeZone.UTC);
}