Java Code Examples for java.time.temporal.TemporalUnit

The following examples show how to use java.time.temporal.TemporalUnit. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: TencentKona-8   Source File: TCKYear.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test_isSupported_TemporalUnit() {
    assertEquals(TEST_2008.isSupported((TemporalUnit) null), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.NANOS), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.MICROS), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.MILLIS), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.SECONDS), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.MINUTES), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.HOURS), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.HALF_DAYS), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.DAYS), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.WEEKS), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.MONTHS), false);
    assertEquals(TEST_2008.isSupported(ChronoUnit.YEARS), true);
    assertEquals(TEST_2008.isSupported(ChronoUnit.DECADES), true);
    assertEquals(TEST_2008.isSupported(ChronoUnit.CENTURIES), true);
    assertEquals(TEST_2008.isSupported(ChronoUnit.MILLENNIA), true);
    assertEquals(TEST_2008.isSupported(ChronoUnit.ERAS), true);
    assertEquals(TEST_2008.isSupported(ChronoUnit.FOREVER), false);
}
 
Example 2
Source Project: jdk8u-jdk   Source File: Duration.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a copy of this duration with the specified duration added.
 * <p>
 * The duration amount is measured in terms of the specified unit.
 * 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. Other units throw an exception.
 * <p>
 * This instance is immutable and unaffected by this method call.
 *
 * @param amountToAdd  the amount to add, measured in terms of the unit, positive or negative
 * @param unit  the unit that the amount is measured in, must have an exact duration, not null
 * @return a {@code Duration} based on this duration with the specified duration added, not null
 * @throws UnsupportedTemporalTypeException if the unit is not supported
 * @throws ArithmeticException if numeric overflow occurs
 */
public Duration plus(long amountToAdd, TemporalUnit unit) {
    Objects.requireNonNull(unit, "unit");
    if (unit == DAYS) {
        return plus(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY), 0);
    }
    if (unit.isDurationEstimated()) {
        throw new UnsupportedTemporalTypeException("Unit must not have an estimated duration");
    }
    if (amountToAdd == 0) {
        return this;
    }
    if (unit instanceof ChronoUnit) {
        switch ((ChronoUnit) unit) {
            case NANOS: return plusNanos(amountToAdd);
            case MICROS: return plusSeconds((amountToAdd / (1000_000L * 1000)) * 1000).plusNanos((amountToAdd % (1000_000L * 1000)) * 1000);
            case MILLIS: return plusMillis(amountToAdd);
            case SECONDS: return plusSeconds(amountToAdd);
        }
        return plusSeconds(Math.multiplyExact(unit.getDuration().seconds, amountToAdd));
    }
    Duration duration = unit.getDuration().multipliedBy(amountToAdd);
    return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano());
}
 
Example 3
@Override
public ChronoLocalDateTimeImpl<D> plus(long amountToAdd, TemporalUnit unit) {
    if (unit instanceof ChronoUnit) {
        ChronoUnit f = (ChronoUnit) unit;
        switch (f) {
            case NANOS: return plusNanos(amountToAdd);
            case MICROS: return plusDays(amountToAdd / MICROS_PER_DAY).plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);
            case MILLIS: return plusDays(amountToAdd / MILLIS_PER_DAY).plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000000);
            case SECONDS: return plusSeconds(amountToAdd);
            case MINUTES: return plusMinutes(amountToAdd);
            case HOURS: return plusHours(amountToAdd);
            case HALF_DAYS: return plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12);  // no overflow (256 is multiple of 2)
        }
        return with(date.plus(amountToAdd, unit), time);
    }
    return ChronoLocalDateTimeImpl.ensureValid(date.getChronology(), unit.addTo(this, amountToAdd));
}
 
Example 4
@Override
public ChronoLocalDateTimeImpl<D> plus(long amountToAdd, TemporalUnit unit) {
    if (unit instanceof ChronoUnit) {
        ChronoUnit f = (ChronoUnit) unit;
        switch (f) {
            case NANOS: return plusNanos(amountToAdd);
            case MICROS: return plusDays(amountToAdd / MICROS_PER_DAY).plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);
            case MILLIS: return plusDays(amountToAdd / MILLIS_PER_DAY).plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000000);
            case SECONDS: return plusSeconds(amountToAdd);
            case MINUTES: return plusMinutes(amountToAdd);
            case HOURS: return plusHours(amountToAdd);
            case HALF_DAYS: return plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12);  // no overflow (256 is multiple of 2)
        }
        return with(date.plus(amountToAdd, unit), time);
    }
    return ChronoLocalDateTimeImpl.ensureValid(date.getChronology(), unit.addTo(this, amountToAdd));
}
 
Example 5
Source Project: jdk8u_jdk   Source File: TCKChronoLocalDate.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="calendars")
public void test_badMinusTemporalUnitChrono(Chronology chrono) {
    LocalDate refDate = LocalDate.of(2013, 1, 1);
    ChronoLocalDate date = chrono.date(refDate);
    for (Chronology[] clist : data_of_calendars()) {
        Chronology chrono2 = clist[0];
        ChronoLocalDate date2 = chrono2.date(refDate);
        TemporalUnit adjuster = new FixedTemporalUnit(date2);
        if (chrono != chrono2) {
            try {
                date.minus(1, adjuster);
                Assert.fail("TemporalUnit.doAdd minus should have thrown a ClassCastException" + date.getClass()
                        + ", can not be cast to " + date2.getClass());
            } catch (ClassCastException cce) {
                // Expected exception; not an error
            }
        } else {
            // Same chronology,
            ChronoLocalDate result = date.minus(1, adjuster);
            assertEquals(result, date2, "WithAdjuster failed to replace date");
        }
    }
}
 
Example 6
Source Project: hottub   Source File: ChronoLocalDate.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @throws DateTimeException {@inheritDoc}
 * @throws ArithmeticException {@inheritDoc}
 */
@Override
default ChronoLocalDate plus(long amountToAdd, TemporalUnit unit) {
    if (unit instanceof ChronoUnit) {
        throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
    }
    return ChronoLocalDateImpl.ensureValid(getChronology(), unit.addTo(this, amountToAdd));
}
 
Example 7
Source Project: jdk8u_jdk   Source File: CopticDate.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
    CopticDate end = getChronology().date(endExclusive);
    if (unit instanceof ChronoUnit) {
        return LocalDate.from(this).until(end, unit);  // TODO: this is wrong
    }
    return unit.between(this, end);
}
 
Example 8
Source Project: jdk8u_jdk   Source File: ChronoPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks if any of the supported units of this period are negative.
 *
 * @return true if any unit of this period is negative
 */
default boolean isNegative() {
    for (TemporalUnit unit : getUnits()) {
        if (get(unit) < 0) {
            return true;
        }
    }
    return false;
}
 
Example 9
Source Project: jdk8u-jdk   Source File: ChronoPeriodImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long get(TemporalUnit unit) {
    if (unit == ChronoUnit.YEARS) {
        return years;
    } else if (unit == ChronoUnit.MONTHS) {
        return months;
    } else if (unit == ChronoUnit.DAYS) {
        return days;
    } else {
        throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
    }
}
 
Example 10
Source Project: jdk8u60   Source File: TCKDuration.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test(groups="{tck}")
public void test_duration_getUnits() {
    Duration duration = Duration.ofSeconds(5000, 1000);
    List<TemporalUnit> units = duration.getUnits();
    assertEquals(units.size(), 2, "Period.getUnits length");
    assertTrue(units.contains(ChronoUnit.SECONDS), "Period.getUnits contains ChronoUnit.SECONDS");
    assertTrue(units.contains(ChronoUnit.NANOS), "contains ChronoUnit.NANOS");
}
 
Example 11
Source Project: jdk8u60   Source File: TCKInstant.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="periodUntilUnit")
public void test_until_TemporalUnit_negated(long seconds1, int nanos1, long seconds2, long nanos2, TemporalUnit unit, long expected) {
    Instant i1 = Instant.ofEpochSecond(seconds1, nanos1);
    Instant i2 = Instant.ofEpochSecond(seconds2, nanos2);
    long amount = i2.until(i1, unit);
    assertEquals(amount, -expected);
}
 
Example 12
private MockSimplePeriod(long amount, TemporalUnit unit) {
    Objects.requireNonNull(unit, "unit");
    if (unit == FOREVER) {
        throw new DateTimeException("Cannot create a period of the Forever unit");
    }
    this.amount = amount;
    this.unit = unit;
}
 
Example 13
Source Project: jdk8u60   Source File: ChronoLocalDate.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @throws DateTimeException {@inheritDoc}
 * @throws ArithmeticException {@inheritDoc}
 */
@Override
default ChronoLocalDate plus(long amountToAdd, TemporalUnit unit) {
    if (unit instanceof ChronoUnit) {
        throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
    }
    return ChronoLocalDateImpl.ensureValid(getChronology(), unit.addTo(this, amountToAdd));
}
 
Example 14
@Override
public long get(TemporalUnit unit) {
    if (unit == ChronoUnit.YEARS) {
        return years;
    } else if (unit == ChronoUnit.MONTHS) {
        return months;
    } else if (unit == ChronoUnit.DAYS) {
        return days;
    } else {
        throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
    }
}
 
Example 15
Source Project: TencentKona-8   Source File: TCKInstant.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="plusTemporalAmount")
public void test_plusTemporalAmount(TemporalUnit unit, TemporalAmount amount, int seconds, int nanos) {
    Instant inst = Instant.ofEpochMilli(1000);
    Instant actual = inst.plus(amount);
    Instant expected = Instant.ofEpochSecond(seconds, nanos);
    assertEquals(actual, expected, "plus(TemporalAmount) failed");
}
 
Example 16
Source Project: jdk8u_jdk   Source File: TCKInstant.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="plusTemporalAmount")
public void test_plusTemporalAmount(TemporalUnit unit, TemporalAmount amount, int seconds, int nanos) {
    Instant inst = Instant.ofEpochMilli(1000);
    Instant actual = inst.plus(amount);
    Instant expected = Instant.ofEpochSecond(seconds, nanos);
    assertEquals(actual, expected, "plus(TemporalAmount) failed");
}
 
Example 17
Source Project: openjdk-jdk8u   Source File: TCKInstant.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="truncatedToInvalid", expectedExceptions=DateTimeException.class)
public void test_truncatedTo_invalid(Instant input, TemporalUnit unit) {
    input.truncatedTo(unit);
}
 
Example 18
Source Project: gama   Source File: GamaDate.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public long until(final Temporal endExclusive, final TemporalUnit unit) {
	return unit.between(internal, endExclusive);
}
 
Example 19
Source Project: jdk8u-dev-jdk   Source File: TCKYearMonth.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="periodUntilUnit")
public void test_until_TemporalUnit_between(YearMonth ym1, YearMonth ym2, TemporalUnit unit, long expected) {
    long amount = unit.between(ym1, ym2);
    assertEquals(amount, expected);
}
 
Example 20
@Override
public TemporalUnit getRangeUnit() {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 21
Source Project: openjdk-8-source   Source File: TCKYear.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="periodUntilUnit")
public void test_until_TemporalUnit(Year year1, Year year2, TemporalUnit unit, long expected) {
    long amount = year1.until(year2, unit);
    assertEquals(amount, expected);
}
 
Example 22
Source Project: hottub   Source File: TCKDuration.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void plus_longTemporalUnit_null() {
   Duration t = Duration.ofSeconds(1);
   t.plus(1, (TemporalUnit) null);
}
 
Example 23
Source Project: TencentKona-8   Source File: TCKOffsetTime.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="periodUntilUnit")
public void test_until_TemporalUnit(OffsetTime offsetTime1, OffsetTime offsetTime2, TemporalUnit unit, long expected) {
    long amount = offsetTime1.until(offsetTime2, unit);
    assertEquals(amount, expected);
}
 
Example 24
Source Project: TencentKona-8   Source File: TCKDuration.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void plus_longTemporalUnit_null() {
   Duration t = Duration.ofSeconds(1);
   t.plus(1, (TemporalUnit) null);
}
 
Example 25
@Test(dataProvider="truncatedToInvalid", expectedExceptions=DateTimeException.class)
public void test_truncatedTo_invalid(Instant input, TemporalUnit unit) {
    input.truncatedTo(unit);
}
 
Example 26
Source Project: dragonwell8_jdk   Source File: TCKYear.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="periodUntilUnit")
public void test_until_TemporalUnit(Year year1, Year year2, TemporalUnit unit, long expected) {
    long amount = year1.until(year2, unit);
    assertEquals(amount, expected);
}
 
Example 27
Source Project: Bytecoder   Source File: LocalDateTime.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a copy of this date-time with the specified amount added.
 * <p>
 * This returns a {@code LocalDateTime}, based on this one, with the amount
 * in terms of the unit added. If it is not possible to add the amount, because the
 * unit is not supported or for some other reason, an exception is thrown.
 * <p>
 * If the field is a {@link ChronoUnit} then the addition is implemented here.
 * Date units are added as per {@link LocalDate#plus(long, TemporalUnit)}.
 * Time units are added as per {@link LocalTime#plus(long, TemporalUnit)} with
 * any overflow in days added equivalent to using {@link #plusDays(long)}.
 * <p>
 * If the field is not a {@code ChronoUnit}, then the result of this method
 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
 * passing {@code this} as the argument. In this case, the unit determines
 * whether and how to perform the addition.
 * <p>
 * This instance is immutable and unaffected by this method call.
 *
 * @param amountToAdd  the amount of the unit to add to the result, may be negative
 * @param unit  the unit of the amount to add, not null
 * @return a {@code LocalDateTime} based on this date-time with the specified amount added, not null
 * @throws DateTimeException if the addition cannot be made
 * @throws UnsupportedTemporalTypeException if the unit is not supported
 * @throws ArithmeticException if numeric overflow occurs
 */
@Override
public LocalDateTime plus(long amountToAdd, TemporalUnit unit) {
    if (unit instanceof ChronoUnit) {
        ChronoUnit f = (ChronoUnit) unit;
        switch (f) {
            case NANOS: return plusNanos(amountToAdd);
            case MICROS: return plusDays(amountToAdd / MICROS_PER_DAY).plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);
            case MILLIS: return plusDays(amountToAdd / MILLIS_PER_DAY).plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000_000);
            case SECONDS: return plusSeconds(amountToAdd);
            case MINUTES: return plusMinutes(amountToAdd);
            case HOURS: return plusHours(amountToAdd);
            case HALF_DAYS: return plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12);  // no overflow (256 is multiple of 2)
        }
        return with(date.plus(amountToAdd, unit), time);
    }
    return unit.addTo(this, amountToAdd);
}
 
Example 28
@Override
public TemporalUnit getBaseUnit() {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 29
Source Project: openjdk-8   Source File: LocalDate.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a copy of this date with the specified amount added.
 * <p>
 * This returns a {@code LocalDate}, based on this one, with the amount
 * in terms of the unit added. If it is not possible to add the amount, because the
 * unit is not supported or for some other reason, an exception is thrown.
 * <p>
 * In some cases, adding the amount can cause the resulting date to become invalid.
 * For example, adding one month to 31st January would result in 31st February.
 * In cases like this, the unit is responsible for resolving the date.
 * Typically it will choose the previous valid date, which would be the last valid
 * day of February in this example.
 * <p>
 * If the field is a {@link ChronoUnit} then the addition is implemented here.
 * The supported fields behave as follows:
 * <ul>
 * <li>{@code DAYS} -
 *  Returns a {@code LocalDate} with the specified number of days added.
 *  This is equivalent to {@link #plusDays(long)}.
 * <li>{@code WEEKS} -
 *  Returns a {@code LocalDate} with the specified number of weeks added.
 *  This is equivalent to {@link #plusWeeks(long)} and uses a 7 day week.
 * <li>{@code MONTHS} -
 *  Returns a {@code LocalDate} with the specified number of months added.
 *  This is equivalent to {@link #plusMonths(long)}.
 *  The day-of-month will be unchanged unless it would be invalid for the new
 *  month and year. In that case, the day-of-month is adjusted to the maximum
 *  valid value for the new month and year.
 * <li>{@code YEARS} -
 *  Returns a {@code LocalDate} with the specified number of years added.
 *  This is equivalent to {@link #plusYears(long)}.
 *  The day-of-month will be unchanged unless it would be invalid for the new
 *  month and year. In that case, the day-of-month is adjusted to the maximum
 *  valid value for the new month and year.
 * <li>{@code DECADES} -
 *  Returns a {@code LocalDate} with the specified number of decades added.
 *  This is equivalent to calling {@link #plusYears(long)} with the amount
 *  multiplied by 10.
 *  The day-of-month will be unchanged unless it would be invalid for the new
 *  month and year. In that case, the day-of-month is adjusted to the maximum
 *  valid value for the new month and year.
 * <li>{@code CENTURIES} -
 *  Returns a {@code LocalDate} with the specified number of centuries added.
 *  This is equivalent to calling {@link #plusYears(long)} with the amount
 *  multiplied by 100.
 *  The day-of-month will be unchanged unless it would be invalid for the new
 *  month and year. In that case, the day-of-month is adjusted to the maximum
 *  valid value for the new month and year.
 * <li>{@code MILLENNIA} -
 *  Returns a {@code LocalDate} with the specified number of millennia added.
 *  This is equivalent to calling {@link #plusYears(long)} with the amount
 *  multiplied by 1,000.
 *  The day-of-month will be unchanged unless it would be invalid for the new
 *  month and year. In that case, the day-of-month is adjusted to the maximum
 *  valid value for the new month and year.
 * <li>{@code ERAS} -
 *  Returns a {@code LocalDate} with the specified number of eras added.
 *  Only two eras are supported so the amount must be one, zero or minus one.
 *  If the amount is non-zero then the year is changed such that the year-of-era
 *  is unchanged.
 *  The day-of-month will be unchanged unless it would be invalid for the new
 *  month and year. In that case, the day-of-month is adjusted to the maximum
 *  valid value for the new month and year.
 * </ul>
 * <p>
 * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
 * <p>
 * If the field is not a {@code ChronoUnit}, then the result of this method
 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
 * passing {@code this} as the argument. In this case, the unit determines
 * whether and how to perform the addition.
 * <p>
 * This instance is immutable and unaffected by this method call.
 *
 * @param amountToAdd  the amount of the unit to add to the result, may be negative
 * @param unit  the unit of the amount to add, not null
 * @return a {@code LocalDate} based on this date with the specified amount added, not null
 * @throws DateTimeException if the addition cannot be made
 * @throws UnsupportedTemporalTypeException if the unit is not supported
 * @throws ArithmeticException if numeric overflow occurs
 */
@Override
public LocalDate plus(long amountToAdd, TemporalUnit unit) {
    if (unit instanceof ChronoUnit) {
        ChronoUnit f = (ChronoUnit) unit;
        switch (f) {
            case DAYS: return plusDays(amountToAdd);
            case WEEKS: return plusWeeks(amountToAdd);
            case MONTHS: return plusMonths(amountToAdd);
            case YEARS: return plusYears(amountToAdd);
            case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
            case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
            case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
            case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
        }
        throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
    }
    return unit.addTo(this, amountToAdd);
}
 
Example 30
@Override
public ThaiBuddhistDate minus(long amountToAdd, TemporalUnit unit) {
    return super.minus(amountToAdd, unit);
}