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

x33g5p2x  于2022-01-18 转载在 其他  
字(8.6k)|赞(0)|评价(0)|浏览(547)

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

ChronoUnit介绍

[英]A standard set of date periods units.

This set of units provide unit-based access to manipulate a date, time or date-time. The standard set of units can be extended by implementing TemporalUnit.

These units are intended to be applicable in multiple calendar systems. For example, most non-ISO calendar systems define units of years, months and days, just with slightly different rules. The documentation of each unit explains how it operates.

Specification for implementors

This is a final, immutable and thread-safe enum.
[中]一组标准的日期周期单位。
这组单元提供基于单元的访问,以操纵日期、时间或日期时间。通过实现临时单元,可以扩展标准单元集。
这些单位适用于多个日历系统。例如,大多数非ISO日历系统定义年、月和日的单位,只是规则略有不同。每台机组的文件说明了其运行方式。
####实施者规范
这是一个最终的、不可变的、线程安全的枚举。

代码示例

代码示例来源:origin: confluentinc/ksql

@Test
public void shouldDeserializeTimeMicrosToBigint() {
 shouldDeserializeTypeCorrectly(
   LogicalTypes.timeMicros().addToSchema(
     org.apache.avro.SchemaBuilder.builder().longType()),
   ChronoUnit.MICROS.between(
     LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT),
     LocalDateTime.now()),
   Schema.OPTIONAL_INT64_SCHEMA
 );
}

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

private Duration nextDurationRaw()
{
  return Duration.ofSeconds( nextLong( DAYS.getDuration().getSeconds() ), nextLong( NANOS_PER_SECOND ) );
}

代码示例来源:origin: google/error-prone

static Optional<ChronoUnit> getInvalidChronoUnit(
  MethodInvocationTree tree, EnumSet<ChronoUnit> invalidUnits) {
 Optional<String> constant = getEnumName(Iterables.getOnlyElement(tree.getArguments()));
 if (constant.isPresent()) {
  for (ChronoUnit invalidTemporalUnit : invalidUnits) {
   if (constant.get().equals(invalidTemporalUnit.name())) {
    return Optional.of(invalidTemporalUnit);
   }
  }
 }
 return Optional.empty();
}

代码示例来源:origin: uk.gov.dstl.baleen/baleen-core

/**
  * Get the uptime
  *
  * @return The time, in seconds, since this StatusMessage was created
  */
 public long getUptime() {
  return ChronoUnit.SECONDS.between(timestamp, LocalDateTime.now());
 }
}

代码示例来源:origin: confluentinc/ksql

@Test
public void shouldDeserializeTimestampToBigint() {
 shouldDeserializeTypeCorrectly(
   LogicalTypes.timestampMillis().addToSchema(
     org.apache.avro.SchemaBuilder.builder().longType()),
   ChronoUnit.MILLIS.between(
     LocalDateTime.of(LocalDate.ofEpochDay(0), LocalTime.MIDNIGHT),
     LocalDateTime.now()),
   Schema.OPTIONAL_INT64_SCHEMA
 );
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Gets the time gap between now and next backup time.
 *
 * @return the time gap to next backup
 */
private long getTimeToNextBackup() {
 LocalDateTime now = LocalDateTime.now(Clock.systemUTC());
 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm");
 LocalTime backupTime = LocalTime.parse(ServerConfiguration
   .get(PropertyKey.MASTER_DAILY_BACKUP_TIME), formatter);
 LocalDateTime nextBackupTime = now.withHour(backupTime.getHour())
   .withMinute(backupTime.getMinute());
 if (nextBackupTime.isBefore(now)) {
  nextBackupTime = nextBackupTime.plusDays(1);
 }
 return ChronoUnit.MILLIS.between(now, nextBackupTime);
}

代码示例来源:origin: hibernate/hibernate-orm

/**
   * Set the transient property at load time based on a calculation.
   * Note that a native Hibernate formula mapping is better for this purpose.
   */
  @PostLoad
  public void calculateAge() {
    age = ChronoUnit.YEARS.between( LocalDateTime.ofInstant(
        Instant.ofEpochMilli( dateOfBirth.getTime()), ZoneOffset.UTC),
      LocalDateTime.now()
    );
  }
}

代码示例来源:origin: tmobile/pacbot

/**
 * Calculates the expiry duration.
 *
 * @param date the date
 * @return the long
 */
private Long calculateExpiryDuration(String date) {
  LocalDate expiryDate = LocalDateTime.parse(date,
      DateTimeFormatter.ofPattern("M/d/yyyy H:m")).toLocalDate();
  LocalDate today = LocalDateTime.now().toLocalDate();
  return java.time.temporal.ChronoUnit.DAYS.between(today, expiryDate);
}

代码示例来源:origin: eventuate-local/eventuate-local

public PublishedEvent waitForEvent(BlockingQueue<PublishedEvent> publishedEvents, Int128 eventId, LocalDateTime deadline, String eventData) throws InterruptedException {
 while (LocalDateTime.now().isBefore(deadline)) {
  long millis = ChronoUnit.MILLIS.between(deadline, LocalDateTime.now());
  PublishedEvent event = publishedEvents.poll(millis, TimeUnit.MILLISECONDS);
  if (event != null && event.getId().equals(eventId.asString()) && eventData.equals(event.getEventData()))
   return event;
 }
 throw new RuntimeException("event not found: " + eventId);
}

代码示例来源:origin: marcelo-mason/PreciousStones

/**
   * Returns the number of minutes of age
   *
   * @return
   */
  public int getAgeInSeconds() {
    ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
    return (int)SECONDS.between(now, age);
  }
}

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

LocalDate startDate;
try {
  startDate = LocalDate.parse(startDateElement.getText(), DateTimeFormatter.ISO_DATE);
} catch (DateTimeParseException e) {
  throw new IllegalArgumentException("Invalid startDate (" + startDateElement.getText() + ").", e);
int startDayOfYear = startDate.getDayOfYear();
int startYear = startDate.getYear();
LocalDate endDate;
try {
      + " must be before endDate (" + endDate + ").");
int maxDayIndex = Math.toIntExact(DAYS.between(startDate, endDate));
int shiftDateSize = maxDayIndex + 1;
List<ShiftDate> shiftDateList = new ArrayList<>(shiftDateSize);

代码示例来源:origin: floragunncom/search-guard

private static long diffDays(LocalDate to) {  
  return ChronoUnit.DAYS.between(LocalDate.now(), to);
}

代码示例来源:origin: com.wuyushuo/vplus-data

/**
 * 获取 {@link LocalDate} 在开始时间和结束时间内的日期时间段 {@link LocalDate} 集合
 * @param start 开始时间
 * @param end 结束时间
 * @return 时间集合
 */
public static List<Date> dateZones(LocalDate start, LocalDate end){
  return Stream.iterate(start, x -> x.plusDays(1))
      .limit(ChronoUnit.DAYS.between(start, end) + 1)
      .map(e -> Date.from(e.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()))
      .collect(Collectors.toList());
}

代码示例来源:origin: confluentinc/ksql

@Test
public void shouldDeserializeDateToInteger() {
 shouldDeserializeTypeCorrectly(
   LogicalTypes.date().addToSchema(
     org.apache.avro.SchemaBuilder.builder().intType()),
   (int) ChronoUnit.DAYS.between(LocalDate.ofEpochDay(0), LocalDate.now()),
   Schema.OPTIONAL_INT32_SCHEMA
 );
}

代码示例来源:origin: kousen/java_8_recipes

public static long daysUntilPirateDay(TemporalAccessor temporal) {
    int day = temporal.get(ChronoField.DAY_OF_MONTH);
    int month = temporal.get(ChronoField.MONTH_OF_YEAR);
    int year = temporal.get(ChronoField.YEAR);
    LocalDate date = LocalDate.of(year, month, day);
    LocalDate tlapd = LocalDate.of(year, Month.SEPTEMBER, 19);
    if (date.isAfter(tlapd)) {
      tlapd = tlapd.plusYears(1);
    }
    return ChronoUnit.DAYS.between(date, tlapd);
  }
}

代码示例来源:origin: stackoverflow.com

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Java8DateExample {
  public static void main(String[] args) throws IOException {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MM yyyy");
    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    final String firstInput = reader.readLine();
    final String secondInput = reader.readLine();
    final LocalDate firstDate = LocalDate.parse(firstInput, formatter);
    final LocalDate secondDate = LocalDate.parse(secondInput, formatter);
    final long days = ChronoUnit.DAYS.between(firstDate, secondDate);
    System.out.println("Days between: " + days);
  }
}

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

LocalDateTime dateTime;
try {
  dateTime = LocalDateTime.parse(startDateTimeString, DATE_FORMAT);
} catch (DateTimeParseException e) {
  throw new IllegalArgumentException("Illegal startDateTimeString (" + startDateTimeString + ").", e);
  referenceDateTime = dateTime;
int dayIndex = (int) ChronoUnit.DAYS.between(referenceDateTime, dateTime);
if (dayIndex < 0) {
  throw new IllegalStateException("The periods should be in ascending order.");

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

nextHeaderCell("Availability");
currentSheet.addMergedRegion(new CellRangeAddress(currentRowNumber, currentRowNumber,
    currentColumnNumber, currentColumnNumber + (int) ChronoUnit.DAYS.between(startDate, endDate) - 1));
nextRow();
nextHeaderCell("");
nextHeaderCell("");
nextHeaderCell("");
for (LocalDate date = startDate; date.compareTo(endDate) < 0; date = date.plusDays(1)) {
  if (date.equals(startDate) || date.getDayOfMonth() == 1) {
    nextHeaderCell(MONTH_FORMATTER.format(date));
    LocalDate startNextMonthDate = date.with(TemporalAdjusters.firstDayOfNextMonth());
        currentColumnNumber, currentColumnNumber + (int) ChronoUnit.DAYS.between(date, startNextMonthDate) - 1));
  } else {
    nextCell();

代码示例来源:origin: Netflix/iceberg

private static long dayToTimestampMicros(int daysFromEpoch) {
 return ChronoUnit.MICROS.between(EPOCH,
   EPOCH_DAY.plusDays(daysFromEpoch).atStartOfDay().atOffset(ZoneOffset.UTC));
}

代码示例来源:origin: prestodb/presto

private static long toDays(int year, int month, int day)
{
  return DAYS.between(LocalDate.of(1970, 1, 1), LocalDate.of(year, month, day));
}

相关文章