org.threeten.bp.Instant类的使用及代码示例

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

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

Instant介绍

[英]An instantaneous point on the time-line.

This class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application.

For practicality, the instant is stored with some constraints. The measurable time-line is restricted to the number of seconds that can be held in a long. This is greater than the current estimated age of the universe. The instant is stored to nanosecond resolution.

The range of an instant requires the storage of a number larger than a long. To achieve this, the class stores a long representing epoch-seconds and an int representing nanosecond-of-second, which will always be between 0 and 999,999,999. The epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Zwhere instants after the epoch have positive values, and earlier instants have negative values. For both the epoch-second and nanosecond parts, a larger value is always later on the time-line than a smaller value.

Time-scale

The length of the solar day is the standard way that humans measure time. This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds, forming a 86400 second day.

Modern timekeeping is based on atomic clocks which precisely define an SI second relative to the transitions of a Caesium atom. The length of an SI second was defined to be very close to the 86400th fraction of a day.

Unfortunately, as the Earth rotates the length of the day varies. In addition, over time the average length of the day is getting longer as the Earth slows. As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds. The actual length of any given day and the amount by which the Earth is slowing are not predictable and can only be determined by measurement. The UT1 time-scale captures the accurate length of day, but is only available some time after the day has completed.

The UTC time-scale is a standard approach to bundle up all the additional fractions of a second from UT1 into whole seconds, known as leap-seconds. A leap-second may be added or removed depending on the Earth's rotational changes. As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where necessary in order to keep the day aligned with the Sun.

The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds. Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and alterations to the length of the notional second. As of 2012, discussions are underway to change the definition of UTC again, with the potential to remove leap seconds or introduce other changes.

Given the complexity of accurate timekeeping described above, this Java API defines its own time-scale with a simplification. The Java time-scale is defined as follows:

  • midday will always be exactly as defined by the agreed international civil time
  • other times during the day will be broadly in line with the agreed international civil time
  • the day will be divided into exactly 86400 subdivisions, referred to as "seconds"
  • the Java "second" may differ from an SI second

Agreed international civil time is the base time-scale agreed by international convention, which in 2012 is UTC (with leap-seconds).

In 2012, the definition of the Java time-scale is the same as UTC for all days except those where a leap-second occurs. On days where a leap-second does occur, the time-scale effectively eliminates the leap-second, maintaining the fiction of 86400 seconds in the day.

The main benefit of always dividing the day into 86400 subdivisions is that it matches the expectations of most users of the API. The alternative is to force every user to understand what a leap second is and to force them to have special logic to handle them. Most applications do not have access to a clock that is accurate enough to record leap-seconds. Most applications also do not have a problem with a second being a very small amount longer or shorter than a real SI second during a leap-second.

If an application does have access to an accurate clock that reports leap-seconds, then the recommended technique to implement the Java time-scale is to use the UTC-SLS convention. UTC-SLS effectively smoothes the leap-second over the last 1000 seconds of the day, making each of the last 1000 "seconds" 1/1000th longer or shorter than a real SI second.

One final problem is the definition of the agreed international civil time before the introduction of modern UTC in 1972. This includes the Java epoch of 1970-01-01. It is intended that instants before 1972 be interpreted based on the solar day divided into 86400 subdivisions.

The Java time-scale is used by all date-time classes. This includes Instant, LocalDate, LocalTime, OffsetDateTime, ZonedDateTime and Duration.

Specification for implementors

This class is immutable and thread-safe.
[中]

代码示例

代码示例来源:origin: googleapis/google-cloud-java

@Override
 public Instant instant() {
  return Instant.ofEpochMilli(currentTimeMillis);
 }
}

代码示例来源:origin: googleapis/google-cloud-java

@Override
public long getDelay(TimeUnit unit) {
 return unit.convert(
   getScheduledTime().toEpochMilli() - clock.millisTime(), TimeUnit.MILLISECONDS);
}

代码示例来源:origin: JakeWharton/ThreeTenABP

public Instant now() {
  return Instant.now();
 }
}

代码示例来源:origin: googleapis/google-cloud-java

if (currTime.isAfter(lastResetTime.plus(windowLength))) {
 int sessionsToKeep =
   Math.max(options.getMinSessions(), maxSessionsInUse + options.getMaxIdleSessions());

代码示例来源:origin: googleapis/google-cloud-java

private void work() {
 Instant cmpTime = Instant.ofEpochMilli(clock.millisTime());
 for (; ; ) {
  PendingCallable<?> callable = null;
  synchronized (pendingCallables) {
   if (pendingCallables.isEmpty()
     || pendingCallables.peek().getScheduledTime().isAfter(cmpTime)) {
    break;
   }
   callable = pendingCallables.poll();
  }
  if (callable != null) {
   try {
    callable.call();
   } catch (Exception e) {
    // We ignore any callable exception, which should be set to the future but not relevant to
    // advanceTime.
   }
  }
 }
 synchronized (pendingCallables) {
  if (shutdown.get() && pendingCallables.isEmpty()) {
   pendingCallables.notifyAll();
  }
 }
}

代码示例来源:origin: googleapis/google-cloud-java

break;
case FIXED_DELAY:
 this.creationTime = Instant.ofEpochMilli(clock.millisTime());
 schedulePendingCallable(this);
 break;
case FIXED_RATE:
 this.creationTime = this.creationTime.plus(delay);
 schedulePendingCallable(this);
 break;

代码示例来源:origin: apache/servicemix-bundles

@Nonnull
  @Override
  public LocalDateTime convert(java.time.Instant source) {
    return LocalDateTime.ofInstant(Instant.ofEpochMilli(source.toEpochMilli()), ZoneOffset.systemDefault());
  }
}

代码示例来源:origin: com.google.api/gax-httpjson

@Override
public ApiFuture<ResponseT> futureCall(RequestT request, ApiCallContext inputContext) {
 Preconditions.checkNotNull(request);
 HttpJsonCallContext context = HttpJsonCallContext.createDefault().nullToSelf(inputContext);
 @Nullable Instant deadline = context.getDeadline();
 // Try to convert the timeout into a deadline and use it if it occurs before the actual deadline
 if (context.getTimeout() != null) {
  @Nonnull Instant newDeadline = Instant.now().plus(context.getTimeout());
  if (deadline == null || newDeadline.isBefore(deadline)) {
   deadline = newDeadline;
  }
 }
 HttpJsonCallOptions callOptions =
   HttpJsonCallOptions.newBuilder()
     .setDeadline(deadline)
     .setCredentials(context.getCredentials())
     .build();
 return context.getChannel().issueFutureUnaryCall(callOptions, request, descriptor);
}

代码示例来源:origin: jeffdcamp/dbtools-android

@Nullable
public static Long localDateTimeToLongUtc(@Nullable LocalDateTime d) {
  if (d == null) {
    return null;
  }
  return d.toInstant(ZoneOffset.UTC).toEpochMilli();
}

代码示例来源:origin: ThreeTen/threetenbp

@Override
  public Instant queryFrom(TemporalAccessor temporal) {
    return Instant.from(temporal);
  }
};

代码示例来源:origin: googleapis/google-cloud-java

private Instant getScheduledTime() {
 return creationTime.plus(delay);
}

代码示例来源:origin: apache/servicemix-bundles

@Nonnull
  @Override
  public LocalDate convert(Date source) {
    return ofInstant(ofEpochMilli(source.getTime()), systemDefault()).toLocalDate();
  }
}

代码示例来源:origin: jeffdcamp/dbtools-android

@Nullable
public static Long localDateTimeToLong(@Nullable LocalDateTime d) {
  if (d == null) {
    return null;
  }
  return d.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}

代码示例来源:origin: riggaroo/android-things-electricity-monitor

private Duration getDifferenceBetweenTimeAndNow(long timeStart) {
  LocalDateTime today = LocalDateTime.now();
  LocalDateTime otherTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timeStart), ZoneId.systemDefault());
  return Duration.between(otherTime, today);
}

代码示例来源:origin: jeffdcamp/dbtools-android

@Test
public void testNow() throws Exception {
  System.out.println("Date:   " + new Date().getTime());
  System.out.println("Joda:   " + DateTime.now().getMillis());
  System.out.println("JSR310: " + Instant.now().toEpochMilli());
}

代码示例来源:origin: apache/servicemix-bundles

@Nonnull
  @Override
  public LocalTime convert(Date source) {
    return ofInstant(ofEpochMilli(source.getTime()), systemDefault()).toLocalTime();
  }
}

代码示例来源:origin: ThreeTen/threetenbp

@Override
public Instant instant() {
  if ((tickNanos % 1000000) == 0) {
    long millis = baseClock.millis();
    return Instant.ofEpochMilli(millis - Jdk8Methods.floorMod(millis, tickNanos / 1000000L));
  }
  Instant instant = baseClock.instant();
  long nanos = instant.getNano();
  long adjust = Jdk8Methods.floorMod(nanos, tickNanos);
  return instant.minusNanos(adjust);
}
@Override

代码示例来源:origin: alexvoronov/geonetworking

/** Returns TAI milliseconds mod 2^32 for the given date.
 *
 * Since java int is signed 32 bit integer, return long instead.
 * It is the same on byte level, but just to avoid confusing people with negative values here.
 *
 *
 * From http://stjarnhimlen.se/comp/time.html:
 *
 * TAI (Temps Atomique International or International Atomic Time) is
 * defined as the weighted average of the time kept by about 200
 * atomic clocks in over 50 national laboratories worldwide.
 * TAI-UT1 was approximately 0 on 1958 Jan 1.
 * (TAI is ahead of UTC by 35 seconds as of 2014.)
 *
 * GPS time = TAI - 19 seconds.  GPS time matched UTC from 1980-01-01
 * to 1981-07-01.  No leap seconds are inserted into GPS time, thus
 * GPS time is 13 seconds ahead of UTC on 2000-01-01.  The GPS epoch
 * is 00:00 (midnight) UTC on 1980-01-06.
 * The difference between GPS Time and UTC changes in increments of
 * seconds each time a leap second is added to UTC time scale.
 */
public static long instantToTaiMillisSince2004Mod32(Instant instantX) {
  OffsetDateTime gnEpochStart =
      OffsetDateTime.of(LocalDateTime.of(2004, Month.JANUARY, 1, 0, 0), ZoneOffset.UTC);
  long millis2004 = gnEpochStart.toInstant().toEpochMilli();
  long millisAtX = instantX.toEpochMilli();
  long taiMillis = (millisAtX + LEAP_SECONDS_SINCE_2004*1000) - millis2004;
  return taiMillis % (1L << 32);
}

代码示例来源:origin: com.github.joschi.jackson/jackson-datatype-threetenbp

@Override
  public Instant apply(FromDecimalArguments a) {
    return Instant.ofEpochSecond(a.integer, a.fraction);
  }
},

代码示例来源:origin: com.torodb.torod.backends/greenplum

@Override
public Void visit(ScalarInstant value, StringBuilder arg) {
  arg.append('\'')
      //this prints the value on ISO-8601, which is the recommended format on PostgreSQL
      .append(value.getValue().toString())
      .append('\'');
  return null;
}

相关文章