java.time.temporal.Temporal类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(12.5k)|赞(0)|评价(0)|浏览(421)

本文整理了Java中java.time.temporal.Temporal类的一些代码示例,展示了Temporal类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Temporal类的具体详情如下:
包路径:java.time.temporal.Temporal
类名称:Temporal

Temporal介绍

[英]Framework-level interface defining read-write access to a temporal object, such as a date, time, offset or some combination of these.

This is the base interface type for date, time and offset objects that are complete enough to be manipulated using plus and minus. It is implemented by those classes that can provide and manipulate information as TemporalField or TemporalQuery. See TemporalAccessor for the read-only version of this interface.

Most date and time information can be represented as a number. These are modeled using TemporalField with the number held using a long to handle large values. Year, month and day-of-month are simple examples of fields, but they also include instant and offsets. See ChronoField for the standard set of fields.

Two pieces of date/time information cannot be represented by numbers, the Chronology and the ZoneId. These can be accessed via #query(TemporalQuery) using the static methods defined on TemporalQueries.

This interface is a framework-level interface that should not be widely used in application code. Instead, applications should create and pass around instances of concrete types, such as LocalDate. There are many reasons for this, part of which is that implementations of this interface may be in calendar systems other than ISO. See ChronoLocalDate for a fuller discussion of the issues.

When to implement

A class should implement this interface if it meets three criteria:

  • it provides access to date/time/offset information, as per TemporalAccessor
  • the set of fields are contiguous from the largest to the smallest
  • the set of fields are complete, such that no other field is needed to define the valid range of values for the fields that are represented

Four examples make this clear:

  • LocalDate implements this interface as it represents a set of fields that are contiguous from days to forever and require no external information to determine the validity of each date. It is therefore able to implement plus/minus correctly.
  • LocalTime implements this interface as it represents a set of fields that are contiguous from nanos to within days and require no external information to determine validity. It is able to implement plus/minus correctly, by wrapping around the day.
  • MonthDay, the combination of month-of-year and day-of-month, does not implement this interface. While the combination is contiguous, from days to months within years, the combination does not have sufficient information to define the valid range of values for day-of-month. As such, it is unable to implement plus/minus correctly.
  • The combination day-of-week and day-of-month ("Friday the 13th") should not implement this interface. It does not represent a contiguous set of fields, as days to weeks overlaps days to months.

Specification for implementors

This interface places no restrictions on the mutability of implementations, however immutability is strongly recommended. All implementations must be Comparable.
[中]框架级接口,定义对时态对象的读写访问,例如日期、时间、偏移量或它们的组合。
这是日期、时间和偏移对象的基本接口类型,这些对象足够完整,可以使用加号和减号进行操作。它由那些可以提供和操作信息的类实现,比如TemporalField或TemporalQuery。有关此接口的只读版本,请参阅TemporalAccessor。
大多数日期和时间信息都可以用数字表示。这些都是使用TemporalField建模的,使用long来处理较大的值。Year、month和day of month是字段的简单示例,但它们也包括instant和Offset。有关标准字段集,请参见ChronoField。
两条日期/时间信息不能用数字表示,即年表和区域ID。可以使用临时查询中定义的静态方法通过#query(临时查询)访问这些数据。
该接口是框架级接口,不应在应用程序代码中广泛使用。相反,应用程序应该创建并传递具体类型的实例,比如LocalDate。这有很多原因,其中一部分原因是该接口的实现可能在ISO以外的日历系统中。有关这些问题的更全面讨论,请参见ChronoLocalDate。
####何时实施
如果类满足以下三个条件,则应实现此接口:
*根据TemporalAccessor,它提供对日期/时间/偏移信息的访问
*字段集从最大到最小是连续的
*字段集是完整的,因此不需要其他字段来定义所表示字段的有效值范围
四个例子说明了这一点:
*LocalDate实现了这个接口,因为它代表了一组从天到永远连续的字段,不需要外部信息来确定每个日期的有效性。因此,它能够正确地执行加减。
*LocalTime实现了这个接口,因为它代表了一组字段,这些字段从nano到几天内是连续的,不需要外部信息来确定有效性。它能够正确地实现加减,只需围绕一天。
*MonthDay是年月日的组合,不实现此接口。虽然该组合是连续的,从几天到几月不等,但该组合没有足够的信息来定义月日的有效值范围。因此,它无法正确执行加减。
*星期五和月日(“13号星期五”)组合不应实现此接口。它并不代表一组连续的字段,因为从天到星期与从天到月重叠。
####实施者规范
这个接口对实现的可变性没有任何限制,但是强烈建议使用不变性。所有实现都必须具有可比性。

代码示例

代码示例来源:origin: jtablesaw/tablesaw

@Override
  @SuppressWarnings("unchecked")
  public T next() {
    final T current = next;
    next = (T) next.plus(by, byUnit);
    num++;
    return current;
  }
};

代码示例来源:origin: neo4j/neo4j

@Override
@SuppressWarnings( "unchecked" )
public final V with( TemporalField field, long newValue )
{
  return replacement( (T) temporal().with( field, newValue ) );
}

代码示例来源:origin: debezium/debezium

/**
 * A utility method that adjusts <a href="https://dev.mysql.com/doc/refman/5.7/en/two-digit-years.html">ambiguous</a> 2-digit
 * year values of DATETIME, DATE, and TIMESTAMP types using these MySQL-specific rules:
 * <ul>
 * <li>Year values in the range 00-69 are converted to 2000-2069.</li>
 * <li>Year values in the range 70-99 are converted to 1970-1999.</li>
 * </ul>
 *
 * @param temporal the temporal instance to adjust; may not be null
 * @return the possibly adjusted temporal instance; never null
 */
protected static Temporal adjustTemporal(Temporal temporal) {
  if (temporal.isSupported(ChronoField.YEAR)) {
    int year = temporal.get(ChronoField.YEAR);
    if (0 <= year && year <= 69) {
      temporal = temporal.plus(2000, ChronoUnit.YEARS);
    } else if (70 <= year && year <= 99) {
      temporal = temporal.plus(1900, ChronoUnit.YEARS);
    }
  }
  return temporal;
}

代码示例来源:origin: neo4j/neo4j

@SuppressWarnings( "unchecked" )
@Override
public <R extends Temporal> R adjustInto( R temporal, long newValue )
{
  int newVal = range.checkValidIntValue( newValue, this );
  int oldYear = temporal.get( ChronoField.YEAR );
  return (R) temporal.with( ChronoField.YEAR, (oldYear / years) * years + newVal )
            .with( TemporalAdjusters.firstDayOfYear() );
}

代码示例来源:origin: neo4j/neo4j

long nanos;
boolean negate = false;
if ( from.isSupported( OFFSET_SECONDS ) && !to.isSupported( OFFSET_SECONDS ) )
int fromNanos = from.isSupported( NANO_OF_SECOND ) ? from.get( NANO_OF_SECOND ) : 0;
int toNanos = to.isSupported( NANO_OF_SECOND ) ? to.get( NANO_OF_SECOND ) : 0;
nanos = toNanos - fromNanos;
    && from.isSupported( SECOND_OF_MINUTE )
    && to.isSupported( SECOND_OF_MINUTE )
    && from.get( SECOND_OF_MINUTE ) != to.get( SECOND_OF_MINUTE );

代码示例来源:origin: neo4j/neo4j

@Override
public final int get( TemporalField field )
{
  int accessor;
  try
  {
   accessor = temporal().get( field );
  }
  catch ( UnsupportedTemporalTypeException e )
  {
    throw new UnsupportedTemporalUnitException( e.getMessage(), e );
  }
  return accessor;
}

代码示例来源:origin: eclipse/smarthome

@Nullable
Temporal isOk(Temporal t) {
  if (checker.matches(t)) {
    return null;
  }
  Temporal out = t.plus(1, type.getBaseUnit());
  // Fall-through switch case. for example if type is year all cases below must also be handled.
  switch (type) {
    case YEAR:
      out = out.with(ChronoField.MONTH_OF_YEAR, 1);
    case MONTH_OF_YEAR:
      out = out.with(ChronoField.DAY_OF_MONTH, 1);
    case DAY_OF_WEEK:
    case DAY_OF_MONTH:
      out = out.with(ChronoField.HOUR_OF_DAY, 0);
    case HOUR_OF_DAY:
      out = out.with(ChronoField.MINUTE_OF_HOUR, 0);
    case MINUTE_OF_HOUR:
      out = out.with(ChronoField.SECOND_OF_MINUTE, 0);
    case SECOND_OF_MINUTE:
      return out;
    default:
      throw new IllegalArgumentException("Invalid field type " + type);
  }
}

代码示例来源:origin: hawkular/hawkular-metrics

public static TemporalAdjuster startOfNextOddHour() {
  return temporal -> {
    int currentHour = temporal.get(ChronoField.HOUR_OF_DAY);
    return temporal.plus((currentHour % 2 == 0) ? 1 : 2, ChronoUnit.HOURS)
        .with(ChronoField.MINUTE_OF_HOUR, 0)
        .with(ChronoField.SECOND_OF_MINUTE, 0)
        .with(ChronoField.NANO_OF_SECOND, 0);
  };
}

代码示例来源:origin: Silverpeas/Silverpeas-Core

private Temporal computeDateForMonthlyFrequencyFrom(final Temporal source,
  DayOfWeekOccurrence dayOfWeek) {
 Temporal current = source;
 if (dayOfWeek.nth() > 1) {
  current = current.with(ChronoField.ALIGNED_WEEK_OF_MONTH, dayOfWeek.nth());
 } else if (dayOfWeek.nth() < 0) {
  current = current.with(ChronoField.DAY_OF_MONTH, 1)
    .plus(1, ChronoUnit.MONTHS)
    .minus(1, ChronoUnit.DAYS)
    .plus(dayOfWeek.nth(), ChronoUnit.WEEKS)
    .with(dayOfWeek.dayOfWeek());
 }
 return current;
}

代码示例来源:origin: kiegroup/optaplanner

@Override
public boolean contains(Temporal_ value) {
  if (value == null || !value.isSupported(incrementUnitType)) {
    return false;
  }
  // We cannot use Temporal.until() to check bounds due to rounding errors
  if (value.compareTo(from) < 0 || value.compareTo(to) >= 0) {
    return false;
  }
  long fromSpace = from.until(value, incrementUnitType);
  if (value.equals(from.plus(fromSpace + 1, incrementUnitType))) {
    // Temporal.until() rounds down, but it needs to round up, to be consistent with Temporal.plus()
    fromSpace++;
  }
  // Only checking the modulus is not enough: 1-MAR + 1 month doesn't include 7-MAR but the modulus is 0 anyway
  return fromSpace % incrementUnitAmount == 0
      && value.equals(from.plus(fromSpace, incrementUnitType));
}

代码示例来源:origin: com.github.seratch/java-time-backport

@Override
  public Temporal adjustInto(Temporal temporal) {
    int calDow = temporal.get(DAY_OF_WEEK);
    if (relative < 2 && calDow == dowValue) {
      return temporal;
    }
    if ((relative & 1) == 0) {
      int daysDiff = calDow - dowValue;
      return temporal.plus(daysDiff >= 0 ? 7 - daysDiff : -daysDiff, DAYS);
    } else {
      int daysDiff = dowValue - calDow;
      return temporal.minus(daysDiff >= 0 ? 7 - daysDiff : -daysDiff, DAYS);
    }
  }
}

代码示例来源:origin: neo4j/neo4j

private static Temporal assertValidMinus( Temporal temporal, long amountToAdd, TemporalUnit unit )
{
  try
  {
    return temporal.minus(amountToAdd,  unit);
  }
  catch ( DateTimeException | ArithmeticException e )
  {
    throw new TemporalArithmeticException( e.getMessage(), e );
  }
}

代码示例来源:origin: hawkular/hawkular-metrics

public static TemporalAdjuster startOfPreviousEvenHour() {
  return temporal -> {
    int currentHour = temporal.get(ChronoField.HOUR_OF_DAY);
    return temporal.minus((currentHour % 2 == 0) ? 0 : 1, ChronoUnit.HOURS)
        .with(ChronoField.MINUTE_OF_HOUR, 0)
        .with(ChronoField.SECOND_OF_MINUTE, 0)
        .with(ChronoField.NANO_OF_SECOND, 0);
  };
}

代码示例来源:origin: neo4j/neo4j

static DurationValue durationBetween( Temporal from, Temporal to )
{
  long months = 0;
  long days = 0;
  if ( from.isSupported( EPOCH_DAY ) && to.isSupported( EPOCH_DAY ) )
  {
    months = assertValidUntil( from, to, ChronoUnit.MONTHS );
    try
    {
      from = from.plus( months, ChronoUnit.MONTHS );
    }
    catch ( DateTimeException | ArithmeticException e )
    {
      throw new TemporalArithmeticException( e.getMessage(), e );
    }
    days = assertValidUntil( from, to, ChronoUnit.DAYS );
    try
    {
      from = from.plus( days, ChronoUnit.DAYS );
    }
    catch ( DateTimeException | ArithmeticException e )
    {
      throw new TemporalArithmeticException( e.getMessage(), e );
    }
  }
  long nanos = assertValidUntil( from, to, NANOS );
  return newDuration( months, days, nanos / NANOS_PER_SECOND, nanos % NANOS_PER_SECOND );
}

代码示例来源:origin: com.nhl.link.rest/link-rest-base

@Override
protected T valueNonNull(JsonNode node) {
  Temporal temporal = ISODateParser.parser().fromString(node.asText());
  GregorianCalendar calendar = new GregorianCalendar();
  calendar.setTimeInMillis(0);
  ZoneId zone = temporal.query(TemporalQueries.zone());
  if (zone != null) {
    calendar.setTimeZone(TimeZone.getTimeZone(zone));
  }
  if (temporal.isSupported(ChronoField.YEAR)) {
    int year = temporal.get(ChronoField.YEAR);
    int monthOfYear = temporal.get(ChronoField.MONTH_OF_YEAR);
    int dayOfMonth = temporal.get(ChronoField.DAY_OF_MONTH);
    calendar.set(year, --monthOfYear, dayOfMonth);
  }
  if (temporal.isSupported(ChronoField.HOUR_OF_DAY)) {
    int hours = temporal.get(ChronoField.HOUR_OF_DAY);
    int minutes = temporal.get(ChronoField.MINUTE_OF_HOUR);
    int seconds = temporal.get(ChronoField.SECOND_OF_MINUTE);
    calendar.set(Calendar.HOUR_OF_DAY, hours);
    calendar.set(Calendar.MINUTE, minutes);
    calendar.set(Calendar.SECOND, seconds);
  }
  if (temporal.isSupported(ChronoField.MILLI_OF_SECOND)) {
    int millis = temporal.get(ChronoField.MILLI_OF_SECOND);
    calendar.setTimeInMillis(calendar.getTimeInMillis() + millis);
  }
  return normalizer.apply(calendar.getTime());
}

代码示例来源:origin: org.threeten/threeten-extra

@Override
  public Temporal adjustInto(Temporal temporal) {
    int dow = temporal.get(DAY_OF_WEEK);
    switch (dow) {
      case 6: //Saturday
        return temporal.minus(1, DAYS);
      case 7:  // Sunday
        return temporal.minus(2, DAYS);
      default:
        return temporal;
    }
  }
}

代码示例来源:origin: org.omnifaces/omniutils

public static TemporalAdjuster nextOrSameDayOfMonth(int dayOfMonth) {
  validateDayOfMonth(dayOfMonth);
  TemporalAdjuster nextDayOfMonth = nextDayOfMonth(dayOfMonth);
  return temporal -> {
    int currentDayOfMonth = temporal.get(DAY_OF_MONTH);
    if (currentDayOfMonth == dayOfMonth || (currentDayOfMonth < dayOfMonth && currentDayOfMonth == temporal.range(DAY_OF_MONTH).getMaximum())) {
      return temporal;
    }
    return temporal.with(nextDayOfMonth);
  };
}

代码示例来源:origin: com.github.seratch/java-time-backport

@Override
public Temporal addTo(Temporal temporal) {
  Jdk8Methods.requireNonNull(temporal, "temporal");
  Chronology temporalChrono = temporal.query(TemporalQueries.chronology());
  if (temporalChrono != null && chronology.equals(temporalChrono) == false) {
    throw new DateTimeException("Invalid chronology, required: " + chronology.getId() + ", but was: " + temporalChrono.getId());
  }
  if (years != 0) {
    temporal = temporal.plus(years, YEARS);
  }
  if (months != 0) {
    temporal = temporal.plus(months, MONTHS);
  }
  if (days != 0) {
    temporal = temporal.plus(days, DAYS);
  }
  return temporal;
}

代码示例来源:origin: neo4j/neo4j

@Override
public final boolean isSupported( TemporalField field )
{
  return temporal().isSupported( field );
}

代码示例来源:origin: dremio/dremio-oss

@Override
 public Temporal adjustInto(Temporal temporal) {
  long adjustedDayOfMonth = Math.min(dayOfMonth, temporal.range(ChronoField.DAY_OF_MONTH).getMaximum());
  return temporal.with(ChronoField.DAY_OF_MONTH, adjustedDayOfMonth);
 }
};

相关文章