Java Code Examples for java.time.temporal.TemporalAccessor#get()

The following examples show how to use java.time.temporal.TemporalAccessor#get() . 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 check out the related API usage on the sidebar.
Example 1
Source File: PartitionByMonth.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public int calculateIndex(String columnValue) {
  TemporalAccessor value = formatter.parse(columnValue);
  switch (type) {
    case DEFAULT:
      return value.get(ChronoField.MONTH_OF_YEAR) - 1;
    case UNLIMITED:
      int targetPartition = ((value.get(ChronoField.YEAR) - beginDate.getYear())
          * 12 + value.get(ChronoField.MONTH_OF_YEAR)
          - beginDate.getMonthValue());
      if (this.partition > 0) {
        targetPartition = reCalculatePartition(targetPartition);
      }
      return targetPartition;
    default:
      throw new MycatException("unsupport type");
  }
}
 
Example 2
Source File: TestReducedParser.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test_reducedWithLateChronoChange() {
    ThaiBuddhistDate date = ThaiBuddhistDate.of(2543, 1, 1);
    DateTimeFormatter df
            = new DateTimeFormatterBuilder()
                    .appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1))
                    .appendLiteral(" ")
                    .appendChronologyId()
            .toFormatter();
    int expected = date.get(YEAR);
    String input = df.format(date);

    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor parsed = df.parseUnresolved(input, pos);
    assertEquals(pos.getIndex(), input.length(), "Input not parsed completely");
    assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)");
    int actual = parsed.get(YEAR);
    assertEquals(actual, expected,
            String.format("Wrong date parsed, chrono: %s, input: %s",
            parsed.query(TemporalQueries.chronology()), input));

}
 
Example 3
Source File: AbstractDateTimeTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test()
public void basicTest_get_TemporalField_supported() {
    for (TemporalAccessor sample : samples()) {
        for (TemporalField field : validFields()) {
            if (sample.range(field).isIntValue()) {
                sample.get(field);  // no exception
            } else {
                try {
                    sample.get(field);
                    fail("Failed on " + sample + " " + field);
                } catch (DateTimeException ex) {
                    // expected
                }
            }
        }
    }
}
 
Example 4
Source File: TestReducedParser.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test_reducedWithLateChronoChangeTwice() {
    DateTimeFormatter df
            = new DateTimeFormatterBuilder()
                    .appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1))
                    .appendLiteral(" ")
                    .appendChronologyId()
                    .appendLiteral(" ")
                    .appendChronologyId()
            .toFormatter();
    int expected = 2044;
    String input = "44 ThaiBuddhist ISO";
    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor parsed = df.parseUnresolved(input, pos);
    assertEquals(pos.getIndex(), input.length(), "Input not parsed completely: " + pos);
    assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)");
    int actual = parsed.get(YEAR);
    assertEquals(actual, expected,
            String.format("Wrong date parsed, chrono: %s, input: %s",
            parsed.query(TemporalQueries.chronology()), input));

}
 
Example 5
Source File: TestReducedParser.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="ReducedWithChrono")
public void test_reducedWithChronoYear(ChronoLocalDate date) {
    Chronology chrono = date.getChronology();
    DateTimeFormatter df
            = new DateTimeFormatterBuilder().appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1))
            .toFormatter()
            .withChronology(chrono);
    int expected = date.get(YEAR);
    String input = df.format(date);

    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor parsed = df.parseUnresolved(input, pos);
    int actual = parsed.get(YEAR);
    assertEquals(actual, expected,
            String.format("Wrong date parsed, chrono: %s, input: %s",
            chrono, input));

}
 
Example 6
Source File: TestReducedParser.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="ReducedWithChrono")
public void test_reducedWithChronoYearOfEra(ChronoLocalDate date) {
    Chronology chrono = date.getChronology();
    DateTimeFormatter df
            = new DateTimeFormatterBuilder().appendValueReduced(YEAR_OF_ERA, 2, 2, LocalDate.of(2000, 1, 1))
            .toFormatter()
            .withChronology(chrono);
    int expected = date.get(YEAR_OF_ERA);
    String input = df.format(date);

    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor parsed = df.parseUnresolved(input, pos);
    int actual = parsed.get(YEAR_OF_ERA);
    assertEquals(actual, expected,
            String.format("Wrong date parsed, chrono: %s, input: %s",
            chrono, input));

}
 
Example 7
Source File: TestReducedParser.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test_reducedWithLateChronoChange() {
    ThaiBuddhistDate date = ThaiBuddhistDate.of(2543, 1, 1);
    DateTimeFormatter df
            = new DateTimeFormatterBuilder()
                    .appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1))
                    .appendLiteral(" ")
                    .appendChronologyId()
            .toFormatter();
    int expected = date.get(YEAR);
    String input = df.format(date);

    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor parsed = df.parseUnresolved(input, pos);
    assertEquals(pos.getIndex(), input.length(), "Input not parsed completely");
    assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)");
    int actual = parsed.get(YEAR);
    assertEquals(actual, expected,
            String.format("Wrong date parsed, chrono: %s, input: %s",
            parsed.query(TemporalQueries.chronology()), input));

}
 
Example 8
Source File: AbstractDateTimeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test()
public void basicTest_get_TemporalField_unsupported() {
    for (TemporalAccessor sample : samples()) {
        for (TemporalField field : invalidFields()) {
            try {
                sample.get(field);
                fail("Failed on " + sample + " " + field);
            } catch (DateTimeException ex) {
                // expected
            }
        }
    }
}
 
Example 9
Source File: PartitionByLatestMonth.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int calculateIndex(String columnValue) {
  TemporalAccessor date = this.formatter.parse(columnValue);
  int day = date.get(ChronoField.DAY_OF_YEAR);
  int hour = date.get(ChronoField.HOUR_OF_DAY);
  return (day - 1) * splitOneDay + hour / hourSpan;
}
 
Example 10
Source File: AbstractDateTimeTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test()
public void basicTest_get_TemporalField_null() {
    for (TemporalAccessor sample : samples()) {
        try {
            sample.get(null);
            fail("Failed on " + sample);
        } catch (NullPointerException ex) {
            // expected
        }
    }
}
 
Example 11
Source File: DateTimeUtility.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private static int getOrDefault(TemporalAccessor temporalAccessor, TemporalField field, int defaultValue) {
    return temporalAccessor.isSupported(field) ? temporalAccessor.get(field) : defaultValue;
}
 
Example 12
Source File: ZonedDateTime.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
/**
 * Obtains an instance of {@code ZonedDateTime} from a temporal object.
 * <p>
 * This obtains a zoned date-time based on the specified temporal.
 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 * which this factory converts to an instance of {@code ZonedDateTime}.
 * <p>
 * The conversion will first obtain a {@code ZoneId} from the temporal object,
 * falling back to a {@code ZoneOffset} if necessary. It will then try to obtain
 * an {@code Instant}, falling back to a {@code LocalDateTime} if necessary.
 * The result will be either the combination of {@code ZoneId} or {@code ZoneOffset}
 * with {@code Instant} or {@code LocalDateTime}.
 * Implementations are permitted to perform optimizations such as accessing
 * those fields that are equivalent to the relevant objects.
 * <p>
 * This method matches the signature of the functional interface {@link TemporalQuery}
 * allowing it to be used as a query via method reference, {@code ZonedDateTime::from}.
 *
 * @param temporal  the temporal object to convert, not null
 * @return the zoned date-time, not null
 * @throws DateTimeException if unable to convert to an {@code ZonedDateTime}
 */
public static ZonedDateTime from(TemporalAccessor temporal) {
    if (temporal instanceof ZonedDateTime) {
        return (ZonedDateTime) temporal;
    }
    try {
        ZoneId zone = ZoneId.from(temporal);
        if (temporal.isSupported(INSTANT_SECONDS)) {
            long epochSecond = temporal.getLong(INSTANT_SECONDS);
            int nanoOfSecond = temporal.get(NANO_OF_SECOND);
            return create(epochSecond, nanoOfSecond, zone);
        } else {
            LocalDate date = LocalDate.from(temporal);
            LocalTime time = LocalTime.from(temporal);
            return of(date, time, zone);
        }
    } catch (DateTimeException ex) {
        throw new DateTimeException("Unable to obtain ZonedDateTime from TemporalAccessor: " +
                temporal + " of type " + temporal.getClass().getName(), ex);
    }
}
 
Example 13
Source File: TestFormatter.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private String test(String fmtStr, Locale locale,
                           String expected, Object dt) {
    String out = new Formatter(
        new StringBuilder(), locale).format(fmtStr, dt).out().toString();
    if (verbose) {
        System.out.printf("%-24s  : %s%n", getClassName(dt), out);
    }

    // expected usually comes from Calendar which only has milliseconds
    // precision. So we're going to replace it's N:[nanos] stamp with
    // the correct value for nanos.
    if ((dt instanceof TemporalAccessor) && expected != null) {
        try {
            // Get millis & nanos from the dt
            final TemporalAccessor ta = (TemporalAccessor) dt;
            final int nanos = ta.get(ChronoField.NANO_OF_SECOND);
            final int millis = ta.get(ChronoField.MILLI_OF_SECOND);
            final String nanstr = String.valueOf(nanos);
            final String mistr = String.valueOf(millis);

            // Compute the value of the N:[nanos] field that we expect
            // to find in 'out'
            final StringBuilder sb = new StringBuilder();
            sb.append("N:[");
            for (int i=nanstr.length(); i<9; i++) {
                sb.append('0');
            }
            sb.append(nanos).append("]");

            // Compute the truncated value of N:[nanos] field that might
            // be in 'expected' when expected was built from Calendar.
            final StringBuilder sbm = new StringBuilder();
            sbm.append("N:[");
            for (int i=mistr.length(); i<3; i++) {
                sbm.append('0');
            }
            sbm.append(mistr).append("000000]");

            // if expected contains the truncated value, replace it with
            // the complete value.
            expected = expected.replace(sbm.toString(), sb.toString());
        } catch (UnsupportedTemporalTypeException e) {
            // nano seconds unsupported - nothing to do...
        }
    }
    if (expected != null && !out.equals(expected)) {
        System.out.printf("%-24s  actual: %s%n                FAILED; expected: %s%n",
                          getClassName(dt), out, expected);
        new RuntimeException().printStackTrace(System.out);
        failure++;
    }
    total++;
    return out;
}
 
Example 14
Source File: ZonedDateTime.java    From desugar_jdk_libs with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Obtains an instance of {@code ZonedDateTime} from a temporal object.
 * <p>
 * This obtains a zoned date-time based on the specified temporal.
 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 * which this factory converts to an instance of {@code ZonedDateTime}.
 * <p>
 * The conversion will first obtain a {@code ZoneId} from the temporal object,
 * falling back to a {@code ZoneOffset} if necessary. It will then try to obtain
 * an {@code Instant}, falling back to a {@code LocalDateTime} if necessary.
 * The result will be either the combination of {@code ZoneId} or {@code ZoneOffset}
 * with {@code Instant} or {@code LocalDateTime}.
 * Implementations are permitted to perform optimizations such as accessing
 * those fields that are equivalent to the relevant objects.
 * <p>
 * This method matches the signature of the functional interface {@link TemporalQuery}
 * allowing it to be used as a query via method reference, {@code ZonedDateTime::from}.
 *
 * @param temporal  the temporal object to convert, not null
 * @return the zoned date-time, not null
 * @throws DateTimeException if unable to convert to an {@code ZonedDateTime}
 */
public static ZonedDateTime from(TemporalAccessor temporal) {
    if (temporal instanceof ZonedDateTime) {
        return (ZonedDateTime) temporal;
    }
    try {
        ZoneId zone = ZoneId.from(temporal);
        if (temporal.isSupported(INSTANT_SECONDS)) {
            long epochSecond = temporal.getLong(INSTANT_SECONDS);
            int nanoOfSecond = temporal.get(NANO_OF_SECOND);
            return create(epochSecond, nanoOfSecond, zone);
        } else {
            LocalDate date = LocalDate.from(temporal);
            LocalTime time = LocalTime.from(temporal);
            return of(date, time, zone);
        }
    } catch (DateTimeException ex) {
        throw new DateTimeException("Unable to obtain ZonedDateTime from TemporalAccessor: " +
                temporal + " of type " + temporal.getClass().getName(), ex);
    }
}
 
Example 15
Source File: ZonedDateTime.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Obtains an instance of {@code ZonedDateTime} from a temporal object.
 * <p>
 * This obtains a zoned date-time based on the specified temporal.
 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 * which this factory converts to an instance of {@code ZonedDateTime}.
 * <p>
 * The conversion will first obtain a {@code ZoneId} from the temporal object,
 * falling back to a {@code ZoneOffset} if necessary. It will then try to obtain
 * an {@code Instant}, falling back to a {@code LocalDateTime} if necessary.
 * The result will be either the combination of {@code ZoneId} or {@code ZoneOffset}
 * with {@code Instant} or {@code LocalDateTime}.
 * Implementations are permitted to perform optimizations such as accessing
 * those fields that are equivalent to the relevant objects.
 * <p>
 * This method matches the signature of the functional interface {@link TemporalQuery}
 * allowing it to be used as a query via method reference, {@code ZonedDateTime::from}.
 *
 * @param temporal  the temporal object to convert, not null
 * @return the zoned date-time, not null
 * @throws DateTimeException if unable to convert to an {@code ZonedDateTime}
 */
public static ZonedDateTime from(TemporalAccessor temporal) {
    if (temporal instanceof ZonedDateTime) {
        return (ZonedDateTime) temporal;
    }
    try {
        ZoneId zone = ZoneId.from(temporal);
        if (temporal.isSupported(INSTANT_SECONDS)) {
            long epochSecond = temporal.getLong(INSTANT_SECONDS);
            int nanoOfSecond = temporal.get(NANO_OF_SECOND);
            return create(epochSecond, nanoOfSecond, zone);
        } else {
            LocalDate date = LocalDate.from(temporal);
            LocalTime time = LocalTime.from(temporal);
            return of(date, time, zone);
        }
    } catch (DateTimeException ex) {
        throw new DateTimeException("Unable to obtain ZonedDateTime from TemporalAccessor: " +
                temporal + " of type " + temporal.getClass().getName(), ex);
    }
}
 
Example 16
Source File: PartitionByMonthAndHistory.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
private int getEndPartition(String endValueText, LocalDate beginDate) {
  TemporalAccessor date = formatter.parse(endValueText);
  return ((date.get(ChronoField.YEAR) - beginDate.getYear())
      * 12 + date.get(ChronoField.MONTH_OF_YEAR)
      - beginDate.getMonthValue());
}
 
Example 17
Source File: FHIRPathAbstractTemporalValue.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private int compareTo(TemporalAccessor left, TemporalAccessor right, ChronoField field) {
    return left.get(field) - right.get(field);
}
 
Example 18
Source File: Instant.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Obtains an instance of {@code Instant} from a temporal object.
 * <p>
 * This obtains an instant based on the specified temporal.
 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 * which this factory converts to an instance of {@code Instant}.
 * <p>
 * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.
 * <p>
 * This method matches the signature of the functional interface {@link TemporalQuery}
 * allowing it to be used as a query via method reference, {@code Instant::from}.
 *
 * @param temporal  the temporal object to convert, not null
 * @return the instant, not null
 * @throws DateTimeException if unable to convert to an {@code Instant}
 */
public static Instant from(TemporalAccessor temporal) {
    if (temporal instanceof Instant) {
        return (Instant) temporal;
    }
    Objects.requireNonNull(temporal, "temporal");
    try {
        long instantSecs = temporal.getLong(INSTANT_SECONDS);
        int nanoOfSecond = temporal.get(NANO_OF_SECOND);
        return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
    } catch (DateTimeException ex) {
        throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " +
                temporal + " of type " + temporal.getClass().getName(), ex);
    }
}
 
Example 19
Source File: Instant.java    From JDKSourceCode1.8 with MIT License 3 votes vote down vote up
/**
 * Obtains an instance of {@code Instant} from a temporal object.
 * <p>
 * This obtains an instant based on the specified temporal.
 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 * which this factory converts to an instance of {@code Instant}.
 * <p>
 * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.
 * <p>
 * This method matches the signature of the functional interface {@link TemporalQuery}
 * allowing it to be used as a query via method reference, {@code Instant::from}.
 *
 * @param temporal  the temporal object to convert, not null
 * @return the instant, not null
 * @throws DateTimeException if unable to convert to an {@code Instant}
 */
public static Instant from(TemporalAccessor temporal) {
    if (temporal instanceof Instant) {
        return (Instant) temporal;
    }
    Objects.requireNonNull(temporal, "temporal");
    try {
        long instantSecs = temporal.getLong(INSTANT_SECONDS);
        int nanoOfSecond = temporal.get(NANO_OF_SECOND);
        return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
    } catch (DateTimeException ex) {
        throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " +
                temporal + " of type " + temporal.getClass().getName(), ex);
    }
}
 
Example 20
Source File: Instant.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Obtains an instance of {@code Instant} from a temporal object.
 * <p>
 * This obtains an instant based on the specified temporal.
 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 * which this factory converts to an instance of {@code Instant}.
 * <p>
 * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.
 * <p>
 * This method matches the signature of the functional interface {@link TemporalQuery}
 * allowing it to be used as a query via method reference, {@code Instant::from}.
 *
 * @param temporal  the temporal object to convert, not null
 * @return the instant, not null
 * @throws DateTimeException if unable to convert to an {@code Instant}
 */
public static Instant from(TemporalAccessor temporal) {
    if (temporal instanceof Instant) {
        return (Instant) temporal;
    }
    Objects.requireNonNull(temporal, "temporal");
    try {
        long instantSecs = temporal.getLong(INSTANT_SECONDS);
        int nanoOfSecond = temporal.get(NANO_OF_SECOND);
        return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
    } catch (DateTimeException ex) {
        throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " +
                temporal + " of type " + temporal.getClass().getName(), ex);
    }
}