java.time.LocalTime.truncatedTo()方法的使用及代码示例

x33g5p2x  于2022-01-23 转载在 其他  
字(11.7k)|赞(0)|评价(0)|浏览(167)

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

LocalTime.truncatedTo介绍

[英]Returns a copy of this LocalTime with the time truncated.

Truncating the time returns a copy of the original time with fields smaller than the specified unit set to zero. For example, truncating with the ChronoUnit#MINUTES unit will set the second-of-minute and nano-of-second field to zero.

The unit must have a TemporalUnit#getDuration()that divides into the length of a standard day without remainder. This includes all supplied time units on ChronoUnit and ChronoUnit#DAYS. Other units throw an exception.

This instance is immutable and unaffected by this method call.
[中]返回此LocalTime的副本,时间被截断。
截断时间将返回原始时间的副本,其中字段小于指定单位并设置为零。例如,使用ChronoUnit#MINUTES单位进行截断会将秒数和秒数字段设置为零。
该单位必须有一个临时单位#getDuration(),它可以划分为一个标准日的长度,没有余数。这包括在ChronoUnit和ChronoUnit#天提供的所有时间单位。其他单位抛出异常。
此实例是不可变的,不受此方法调用的影响。

代码示例

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

static Pair<LocalDate,LocalTime> getTruncatedDateAndTime( TemporalUnit unit, TemporalValue input, String type )
{
  if ( unit.isTimeBased() && !(input instanceof DateTimeValue || input instanceof LocalDateTimeValue) )
  {
    throw new UnsupportedTemporalUnitException( String.format( "Cannot truncate %s to %s with a time based unit.", input, type ) );
  }
  LocalDate localDate = input.getDatePart();
  LocalTime localTime = input.hasTime() ? input.getLocalTimePart() : LocalTimeValue.DEFAULT_LOCAL_TIME;
  LocalTime truncatedTime;
  LocalDate truncatedDate;
  if ( unit.isDateBased() )
  {
    truncatedDate = DateValue.truncateTo( localDate, unit );
    truncatedTime = LocalTimeValue.DEFAULT_LOCAL_TIME;
  }
  else
  {
    truncatedDate = localDate;
    truncatedTime = localTime.truncatedTo( unit );
  }
  return Pair.of( truncatedDate, truncatedTime );
}

代码示例来源:origin: apache/avro

@Test
public void testRecordWithJsr310LogicalTypes() throws IOException {
 TestRecordWithJsr310LogicalTypes record = new TestRecordWithJsr310LogicalTypes(
   true,
   34,
   35L,
   3.14F,
   3019.34,
   null,
   java.time.LocalDate.now(),
   java.time.LocalTime.now().truncatedTo(ChronoUnit.MILLIS),
   java.time.Instant.now().truncatedTo(ChronoUnit.MILLIS),
   new BigDecimal(123.45f).setScale(2, RoundingMode.HALF_DOWN)
 );
 File data = write(TestRecordWithJsr310LogicalTypes.getClassSchema(), record);
 List<TestRecordWithJsr310LogicalTypes> actual = read(
   TestRecordWithJsr310LogicalTypes.getClassSchema(), data);
 Assert.assertEquals("Should match written record", record, actual.get(0));
}

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

public static LocalTimeValue truncate(
    TemporalUnit unit,
    TemporalValue input,
    MapValue fields,
    Supplier<ZoneId> defaultZone )
{
  LocalTime localTime = input.getLocalTimePart();
  LocalTime truncatedLT = assertValidUnit( () -> localTime.truncatedTo( unit ) );
  if ( fields.size() == 0 )
  {
    return localTime( truncatedLT );
  }
  else
  {
    return updateFieldMapWithConflictingSubseconds( fields, unit, truncatedLT,
        ( mapValue, localTime1 ) -> {
          if ( mapValue.size() == 0 )
          {
            return localTime( localTime1 );
          }
          else
          {
            return build( mapValue.updatedWith( "time", localTime( localTime1 ) ), defaultZone );
          }
        } );
  }
}

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

@Test
public void testTruncatedTo() {
  List<LocalTime> times = ImmutableList.of(
      LocalTime.of(5, 11, 24),
      LocalTime.of(21, 11, 24),
      LocalTime.MIDNIGHT,
      LocalTime.NOON,
      LocalTime.MIN,
      LocalTime.MAX);
  for (LocalTime time : times) {
    assertEquals(time.truncatedTo(SECONDS),
        asLocalTime(truncatedTo(SECONDS, pack(time))));
    assertEquals(time.truncatedTo(MINUTES),
        asLocalTime(truncatedTo(MINUTES, pack(time))));
    assertEquals(time.truncatedTo(HOURS),
        asLocalTime(truncatedTo(HOURS, pack(time))));
    assertEquals(time.truncatedTo(HALF_DAYS),
        asLocalTime(truncatedTo(HALF_DAYS, pack(time))));
    assertEquals(time.truncatedTo(DAYS),
        asLocalTime(truncatedTo(DAYS, pack(time))));
  }
}

代码示例来源:origin: apache/avro

null,
java.time.LocalDate.now(),
java.time.LocalTime.now().truncatedTo(ChronoUnit.MILLIS),
java.time.Instant.now().truncatedTo(ChronoUnit.MILLIS),
new BigDecimal(123.45f).setScale(2, RoundingMode.HALF_DOWN)

代码示例来源:origin: com.sqlapp/sqlapp-core

/**
 * ミリ秒以下を切り捨てます
 * 
 * @param date
 *            日付
 * @return 時刻情報を切り捨てた日付
 */
public static LocalTime truncateMilisecond(final LocalTime date) {
  if (date == null) {
    return null;
  }
  return date.truncatedTo(ChronoUnit.SECONDS);
}

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

@Override
protected boolean encodeNonNullObject(Object object, JsonGenerator out) throws IOException {
  LocalTime time = (LocalTime) object;
  String formatted = time.truncatedTo(ChronoUnit.SECONDS).toString();
  out.writeObject(formatted);
  return true;
}

代码示例来源:origin: openhab/openhab-core

public TimeOfDayConditionHandler(Condition condition) {
  super(condition);
  Configuration configuration = module.getConfiguration();
  String startTimeConfig = (String) configuration.get(START_TIME);
  String endTimeConfig = (String) configuration.get(END_TIME);
  startTime = startTimeConfig == null ? null : LocalTime.parse(startTimeConfig).truncatedTo(ChronoUnit.MINUTES);
  endTime = endTimeConfig == null ? null : LocalTime.parse(endTimeConfig).truncatedTo(ChronoUnit.MINUTES);
}

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

/**
 * Returns a copy of this {@code LocalDateTime} with the time truncated.
 * <p>
 * Truncation returns a copy of the original date-time with fields
 * smaller than the specified unit set to zero.
 * For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit
 * will set the second-of-minute and nano-of-second field to zero.
 * <p>
 * The unit must have a {@linkplain TemporalUnit#getDuration() duration}
 * that divides into the length of a standard day without remainder.
 * This includes all supplied time units on {@link ChronoUnit} and
 * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.
 * <p>
 * This instance is immutable and unaffected by this method call.
 *
 * @param unit  the unit to truncate to, not null
 * @return a {@code LocalDateTime} based on this date-time with the time truncated, not null
 * @throws DateTimeException if unable to truncate
 */
public LocalDateTime truncatedTo(TemporalUnit unit) {
  return with(date, time.truncatedTo(unit));
}

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

/**
 * Returns a copy of this {@code OffsetTime} with the time truncated.
 * <p>
 * Truncation returns a copy of the original time with fields
 * smaller than the specified unit set to zero.
 * For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit
 * will set the second-of-minute and nano-of-second field to zero.
 * <p>
 * The unit must have a {@linkplain TemporalUnit#getDuration() duration}
 * that divides into the length of a standard day without remainder.
 * This includes all supplied time units on {@link ChronoUnit} and
 * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.
 * <p>
 * The offset does not affect the calculation and will be the same in the result.
 * <p>
 * This instance is immutable and unaffected by this method call.
 *
 * @param unit  the unit to truncate to, not null
 * @return an {@code OffsetTime} based on this time with the time truncated, not null
 * @throws DateTimeException if unable to truncate
 */
public OffsetTime truncatedTo(TemporalUnit unit) {
  return with(time.truncatedTo(unit), offset);
}

代码示例来源:origin: jneat/mybatis-types

@DataProvider(name = "time")
public synchronized Object[][] timeData() {
  if (timeCache == null) {
    timeCache = new Object[][]{
      new Object[]{10L, null, null},
      new Object[]{11L, Instant.now(), LocalTime.now().truncatedTo(ChronoUnit.SECONDS)},};
  }
  return timeCache;
}

代码示例来源:origin: com.enonic.xp/core-api

private static LocalTime convertToLocalTime( final Object value )
{
  if ( value instanceof Instant )
  {
    return LocalDateTime.ofInstant( (Instant) value, ZoneOffset.UTC ).toLocalTime().truncatedTo( ChronoUnit.MINUTES );
  }
  if ( value instanceof LocalTime )
  {
    return (LocalTime) value;
  }
  if ( value instanceof LocalDate )
  {
    return ( (LocalDate) value ).atStartOfDay().toLocalTime();
  }
  if ( value instanceof LocalDateTime )
  {
    return LocalTime.of( ( (LocalDateTime) value ).getHour(), ( (LocalDateTime) value ).getMinute(),
               ( (LocalDateTime) value ).getSecond() );
  }
  else if ( value instanceof String )
  {
    return LocalTime.parse( (String) value, LOCAL_TIME_FORMATTER );
  }
  else
  {
    return null;
  }
}

代码示例来源:origin: openhab/openhab-core

LocalTime currentTime = LocalTime.now().truncatedTo(ChronoUnit.MINUTES);
  logger.debug("Time condition with id {} evaluated, that {} is between {} and {}, or between {} and {}.",
      module.getId(), currentTime, LocalTime.MIDNIGHT, endTime, startTime,
      LocalTime.MAX.truncatedTo(ChronoUnit.MINUTES));
  return true;

代码示例来源:origin: org.neo4j/neo4j-values

static Pair<LocalDate,LocalTime> getTruncatedDateAndTime( TemporalUnit unit, TemporalValue input, String type )
{
  if ( unit.isTimeBased() && !(input instanceof DateTimeValue || input instanceof LocalDateTimeValue) )
  {
    throw new UnsupportedTemporalUnitException( String.format( "Cannot truncate %s to %s with a time based unit.", input, type ) );
  }
  LocalDate localDate = input.getDatePart();
  LocalTime localTime = input.hasTime() ? input.getLocalTimePart() : LocalTimeValue.DEFAULT_LOCAL_TIME;
  LocalTime truncatedTime;
  LocalDate truncatedDate;
  if ( unit.isDateBased() )
  {
    truncatedDate = DateValue.truncateTo( localDate, unit );
    truncatedTime = LocalTimeValue.DEFAULT_LOCAL_TIME;
  }
  else
  {
    truncatedDate = localDate;
    truncatedTime = localTime.truncatedTo( unit );
  }
  return Pair.of( truncatedDate, truncatedTime );
}

代码示例来源:origin: org.dbflute/dbflute-runtime

protected Object filterConditionValueIfNeeds(ConditionKey key, Object value, ConditionValue cvalue, String columnDbName,
    ConditionOption option, ColumnInfo columnInfo) {
  if (value != null && isDatetimePrecisionTruncationOfConditionEnabled(columnDbName)) { // null check, just in case
    if (columnInfo.isObjectNativeTypeDate()) { // contains Java8 Dates
      final Integer datetimePrecision = columnInfo.getDatetimePrecision();
      if (datetimePrecision == null || datetimePrecision == 0) { // non-millisecond date-time
        if (value instanceof LocalDateTime) {
          return ((LocalDateTime) value).truncatedTo(ChronoUnit.SECONDS); // means clear millisecond
        } else if (value instanceof LocalTime) {
          return ((LocalTime) value).truncatedTo(ChronoUnit.SECONDS); // means clear millisecond
        } else if (value instanceof Date && !(value instanceof java.sql.Date)) {
          final Calendar cal = DfTypeUtil.toCalendar(value);
          DfTypeUtil.clearCalendarMillisecond(cal);
          return DfTypeUtil.toDate(cal);
        }
      }
    }
  }
  return value;
}

代码示例来源:origin: fbacchella/LogHub

lt = LocalTime.now(zi);
lt = lt.truncatedTo(ChronoUnit.SECONDS);

代码示例来源:origin: org.jline/jline

sb.append("  ");
LocalTime lt = LocalTime.from(entry.time().atZone(ZoneId.systemDefault()))
    .truncatedTo(ChronoUnit.SECONDS);
DateTimeFormatter.ISO_LOCAL_TIME.formatTo(lt, sb);

代码示例来源:origin: org.jline/jline-builtins

sb.append("  ");
LocalTime lt = LocalTime.from(entry.time().atZone(ZoneId.systemDefault()))
    .truncatedTo(ChronoUnit.SECONDS);
DateTimeFormatter.ISO_LOCAL_TIME.formatTo(lt, sb);

代码示例来源:origin: arnaudroger/SimpleFlatMapper

@Test
public void testObjectToLocalTime() throws Exception {
  ZoneId zoneId = ZoneId.systemDefault();
  LocalTime localTime = LocalTime.now(zoneId);
  ZoneOffset offset = zoneId.getRules().getOffset(localTime.atDate(LocalDate.now()));
  testObjectToLocalTime(null, null);
  testObjectToLocalTime(localTime, localTime);
  testObjectToLocalTime(localTime.atDate(LocalDate.now()), localTime);
  testObjectToLocalTime(localTime.atDate(LocalDate.now()).atZone(zoneId), localTime);
  testObjectToLocalTime(localTime.atDate(LocalDate.now()).atOffset(offset), localTime);
  testObjectToLocalTime(localTime.atDate(LocalDate.now()).toLocalTime(), localTime);
  testObjectToLocalTime(localTime.atDate(LocalDate.now()).toInstant(offset), localTime);
  testObjectToLocalTime(Date.from(localTime.atDate(LocalDate.now()).toInstant(offset)), localTime.truncatedTo(ChronoUnit.MILLIS));
  try {
    testObjectToLocalTime("a string", localTime);
    fail();
  } catch (IllegalArgumentException e) {
    // expected
  }
}

代码示例来源:origin: org.neo4j/neo4j-values

public static LocalTimeValue truncate(
    TemporalUnit unit,
    TemporalValue input,
    MapValue fields,
    Supplier<ZoneId> defaultZone )
{
  LocalTime localTime = input.getLocalTimePart();
  LocalTime truncatedLT = assertValidUnit( () -> localTime.truncatedTo( unit ) );
  if ( fields.size() == 0 )
  {
    return localTime( truncatedLT );
  }
  else
  {
    return updateFieldMapWithConflictingSubseconds( fields, unit, truncatedLT,
        ( mapValue, localTime1 ) -> {
          if ( mapValue.size() == 0 )
          {
            return localTime( localTime1 );
          }
          else
          {
            return build( mapValue.updatedWith( "time", localTime( localTime1 ) ), defaultZone );
          }
        } );
  }
}

相关文章