Search in sources :

Example 26 with TemporalUnit

use of java.time.temporal.TemporalUnit in project j2objc by google.

the class TCKPeriod method factory_from_TemporalAmount_YearsDays.

@Test
public void factory_from_TemporalAmount_YearsDays() {
    TemporalAmount amount = new TemporalAmount() {

        @Override
        public long get(TemporalUnit unit) {
            if (unit == YEARS) {
                return 23;
            } else {
                return 45;
            }
        }

        @Override
        public List<TemporalUnit> getUnits() {
            List<TemporalUnit> list = new ArrayList<>();
            list.add(YEARS);
            list.add(DAYS);
            return list;
        }

        @Override
        public Temporal addTo(Temporal temporal) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Temporal subtractFrom(Temporal temporal) {
            throw new UnsupportedOperationException();
        }
    };
    assertPeriod(Period.from(amount), 23, 0, 45);
}
Also used : Temporal(java.time.temporal.Temporal) TemporalUnit(java.time.temporal.TemporalUnit) TemporalAmount(java.time.temporal.TemporalAmount) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 27 with TemporalUnit

use of java.time.temporal.TemporalUnit in project j2objc by google.

the class TCKPeriod method test_minus_TemporalAmount_DaysHours.

/* J2ObjC removed: Only "gregorian" and "julian" calendars are supported.
    @Test(expected = DateTimeException.class)
    public void test_minus_TemporalAmount_nonISO() {
        pymd(4, 5, 6).minus(ThaiBuddhistChronology.INSTANCE.period(1, 0, 0));
    } */
@Test(expected = DateTimeException.class)
public void test_minus_TemporalAmount_DaysHours() {
    TemporalAmount amount = new TemporalAmount() {

        @Override
        public long get(TemporalUnit unit) {
            if (unit == DAYS) {
                return 1;
            } else {
                return 2;
            }
        }

        @Override
        public List<TemporalUnit> getUnits() {
            List<TemporalUnit> list = new ArrayList<>();
            list.add(DAYS);
            list.add(HOURS);
            return list;
        }

        @Override
        public Temporal addTo(Temporal temporal) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Temporal subtractFrom(Temporal temporal) {
            throw new UnsupportedOperationException();
        }
    };
    pymd(4, 5, 6).minus(amount);
}
Also used : Temporal(java.time.temporal.Temporal) TemporalUnit(java.time.temporal.TemporalUnit) TemporalAmount(java.time.temporal.TemporalAmount) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 28 with TemporalUnit

use of java.time.temporal.TemporalUnit in project j2objc by google.

the class Period method from.

// -----------------------------------------------------------------------
/**
 * Obtains an instance of {@code Period} from a temporal amount.
 * <p>
 * This obtains a period based on the specified amount.
 * A {@code TemporalAmount} represents an  amount of time, which may be
 * date-based or time-based, which this factory extracts to a {@code Period}.
 * <p>
 * The conversion loops around the set of units from the amount and uses
 * the {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS}
 * and {@link ChronoUnit#DAYS DAYS} units to create a period.
 * If any other units are found then an exception is thrown.
 * <p>
 * If the amount is a {@code ChronoPeriod} then it must use the ISO chronology.
 *
 * @param amount  the temporal amount to convert, not null
 * @return the equivalent period, not null
 * @throws DateTimeException if unable to convert to a {@code Period}
 * @throws ArithmeticException if the amount of years, months or days exceeds an int
 */
public static Period from(TemporalAmount amount) {
    if (amount instanceof Period) {
        return (Period) amount;
    }
    if (amount instanceof ChronoPeriod) {
        if (IsoChronology.INSTANCE.equals(((ChronoPeriod) amount).getChronology()) == false) {
            throw new DateTimeException("Period requires ISO chronology: " + amount);
        }
    }
    Objects.requireNonNull(amount, "amount");
    int years = 0;
    int months = 0;
    int days = 0;
    for (TemporalUnit unit : amount.getUnits()) {
        long unitAmount = amount.get(unit);
        if (unit == ChronoUnit.YEARS) {
            years = Math.toIntExact(unitAmount);
        } else if (unit == ChronoUnit.MONTHS) {
            months = Math.toIntExact(unitAmount);
        } else if (unit == ChronoUnit.DAYS) {
            days = Math.toIntExact(unitAmount);
        } else {
            throw new DateTimeException("Unit must be Years, Months or Days, but was " + unit);
        }
    }
    return create(years, months, days);
}
Also used : ChronoPeriod(java.time.chrono.ChronoPeriod) TemporalUnit(java.time.temporal.TemporalUnit) ChronoPeriod(java.time.chrono.ChronoPeriod)

Example 29 with TemporalUnit

use of java.time.temporal.TemporalUnit in project j2objc by google.

the class Duration method from.

// -----------------------------------------------------------------------
/**
 * Obtains an instance of {@code Duration} from a temporal amount.
 * <p>
 * This obtains a duration based on the specified amount.
 * A {@code TemporalAmount} represents an  amount of time, which may be
 * date-based or time-based, which this factory extracts to a duration.
 * <p>
 * The conversion loops around the set of units from the amount and uses
 * the {@linkplain TemporalUnit#getDuration() duration} of the unit to
 * calculate the total {@code Duration}.
 * Only a subset of units are accepted by this method. The unit must either
 * have an {@linkplain TemporalUnit#isDurationEstimated() exact duration}
 * or be {@link ChronoUnit#DAYS} which is treated as 24 hours.
 * If any other units are found then an exception is thrown.
 *
 * @param amount  the temporal amount to convert, not null
 * @return the equivalent duration, not null
 * @throws DateTimeException if unable to convert to a {@code Duration}
 * @throws ArithmeticException if numeric overflow occurs
 */
public static Duration from(TemporalAmount amount) {
    Objects.requireNonNull(amount, "amount");
    Duration duration = ZERO;
    for (TemporalUnit unit : amount.getUnits()) {
        duration = duration.plus(amount.get(unit), unit);
    }
    return duration;
}
Also used : TemporalUnit(java.time.temporal.TemporalUnit)

Example 30 with TemporalUnit

use of java.time.temporal.TemporalUnit in project hive by apache.

the class HiveSqlDateTimeFormatter method verifyForParse.

/**
 * Make sure the generated list of tokens is valid for parsing strings to datetime objects.
 */
private void verifyForParse() {
    // create a list of tokens' temporal fields
    List<TemporalField> temporalFields = new ArrayList<>();
    List<TemporalUnit> timeZoneTemporalUnits = new ArrayList<>();
    int roundYearCount = 0, yearCount = 0;
    boolean containsIsoFields = false, containsGregorianFields = false;
    for (Token token : tokens) {
        if (token.temporalField != null) {
            temporalFields.add(token.temporalField);
            if (token.temporalField == ChronoField.YEAR) {
                if (token.string.startsWith("r")) {
                    roundYearCount += 1;
                } else {
                    yearCount += 1;
                }
            }
            if (token.temporalField.isDateBased() && token.temporalField != ChronoField.DAY_OF_WEEK) {
                if (ISO_8601_TEMPORAL_FIELDS.contains(token.temporalField)) {
                    containsIsoFields = true;
                } else {
                    containsGregorianFields = true;
                }
            }
        } else if (token.temporalUnit != null) {
            timeZoneTemporalUnits.add(token.temporalUnit);
        }
    }
    // check for illegal temporal fields
    if (temporalFields.contains(IsoFields.QUARTER_OF_YEAR)) {
        throw new IllegalArgumentException("Illegal field: q (" + IsoFields.QUARTER_OF_YEAR + ")");
    }
    if (temporalFields.contains(WeekFields.SUNDAY_START.dayOfWeek())) {
        throw new IllegalArgumentException("Illegal field: d (" + WeekFields.SUNDAY_START.dayOfWeek() + ")");
    }
    if (temporalFields.contains(ChronoField.DAY_OF_WEEK) && containsGregorianFields) {
        throw new IllegalArgumentException("Illegal field: dy/day (" + ChronoField.DAY_OF_WEEK + ")");
    }
    if (temporalFields.contains(ChronoField.ALIGNED_WEEK_OF_MONTH)) {
        throw new IllegalArgumentException("Illegal field: w (" + ChronoField.ALIGNED_WEEK_OF_MONTH + ")");
    }
    if (temporalFields.contains(ChronoField.ALIGNED_WEEK_OF_YEAR)) {
        throw new IllegalArgumentException("Illegal field: ww (" + ChronoField.ALIGNED_WEEK_OF_YEAR + ")");
    }
    if (containsGregorianFields && containsIsoFields) {
        throw new IllegalArgumentException("Pattern cannot contain both ISO and Gregorian tokens");
    }
    if (!(temporalFields.contains(ChronoField.YEAR) || temporalFields.contains(IsoFields.WEEK_BASED_YEAR))) {
        throw new IllegalArgumentException("Missing year token.");
    }
    if (containsGregorianFields && !(temporalFields.contains(ChronoField.MONTH_OF_YEAR) && temporalFields.contains(ChronoField.DAY_OF_MONTH) || temporalFields.contains(ChronoField.DAY_OF_YEAR))) {
        throw new IllegalArgumentException("Missing day of year or (month of year + day of month)" + " tokens.");
    }
    if (containsIsoFields && !(temporalFields.contains(IsoFields.WEEK_OF_WEEK_BASED_YEAR) && temporalFields.contains(ChronoField.DAY_OF_WEEK))) {
        throw new IllegalArgumentException("Missing week of year (iw) or day of week (id) tokens.");
    }
    if (roundYearCount > 0 && yearCount > 0) {
        throw new IllegalArgumentException("Invalid duplication of format element: Both year and" + "round year are provided");
    }
    for (TemporalField tokenType : temporalFields) {
        if (Collections.frequency(temporalFields, tokenType) > 1) {
            throw new IllegalArgumentException("Invalid duplication of format element: multiple " + tokenType + " tokens provided.");
        }
    }
    if (temporalFields.contains(ChronoField.AMPM_OF_DAY) && !(temporalFields.contains(ChronoField.HOUR_OF_DAY) || temporalFields.contains(ChronoField.HOUR_OF_AMPM))) {
        throw new IllegalArgumentException("AM/PM provided but missing hour token.");
    }
    if (temporalFields.contains(ChronoField.AMPM_OF_DAY) && temporalFields.contains(ChronoField.HOUR_OF_DAY)) {
        throw new IllegalArgumentException("Conflict between median indicator and hour token.");
    }
    if (temporalFields.contains(ChronoField.HOUR_OF_AMPM) && temporalFields.contains(ChronoField.HOUR_OF_DAY)) {
        throw new IllegalArgumentException("Conflict between hour of day and hour of am/pm token.");
    }
    if (temporalFields.contains(ChronoField.DAY_OF_YEAR) && (temporalFields.contains(ChronoField.DAY_OF_MONTH) || temporalFields.contains(ChronoField.MONTH_OF_YEAR))) {
        throw new IllegalArgumentException("Day of year provided with day or month token.");
    }
    if (temporalFields.contains(ChronoField.SECOND_OF_DAY) && (temporalFields.contains(ChronoField.HOUR_OF_DAY) || temporalFields.contains(ChronoField.HOUR_OF_AMPM) || temporalFields.contains(ChronoField.MINUTE_OF_HOUR) || temporalFields.contains(ChronoField.SECOND_OF_MINUTE))) {
        throw new IllegalArgumentException("Second of day token conflicts with other token(s).");
    }
    if (timeZoneTemporalUnits.contains(ChronoUnit.MINUTES) && !timeZoneTemporalUnits.contains(ChronoUnit.HOURS)) {
        throw new IllegalArgumentException("Time zone minute token provided without time zone hour token.");
    }
}
Also used : TemporalField(java.time.temporal.TemporalField) TemporalUnit(java.time.temporal.TemporalUnit) ArrayList(java.util.ArrayList)

Aggregations

TemporalUnit (java.time.temporal.TemporalUnit)60 LocalDate (java.time.LocalDate)18 Test (org.junit.Test)18 Test (org.testng.annotations.Test)17 Temporal (java.time.temporal.Temporal)16 TemporalAmount (java.time.temporal.TemporalAmount)15 Chronology (java.time.chrono.Chronology)12 IsoChronology (java.time.chrono.IsoChronology)12 ArrayList (java.util.ArrayList)12 UseDataProvider (com.tngtech.java.junit.dataprovider.UseDataProvider)6 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)6 DateTimeException (java.time.DateTimeException)6 HijrahChronology (java.time.chrono.HijrahChronology)6 JapaneseChronology (java.time.chrono.JapaneseChronology)6 MinguoChronology (java.time.chrono.MinguoChronology)6 ThaiBuddhistChronology (java.time.chrono.ThaiBuddhistChronology)6 Matcher (java.util.regex.Matcher)6 Pattern (java.util.regex.Pattern)6 Duration (java.time.Duration)5 ChronoLocalDate (java.time.chrono.ChronoLocalDate)4