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

x33g5p2x  于2022-01-20 转载在 其他  
字(15.1k)|赞(0)|评价(0)|浏览(249)

本文整理了Java中java.time.Instant类的一些代码示例,展示了Instant类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Instant类的具体详情如下:
包路径:java.time.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.
[中]时间线上的瞬时点。
此类为时间线上的单个瞬时点建模。这可能用于记录应用程序中的事件时间戳。
出于实用性考虑,瞬间存储时带有一些约束。可测量的时间线仅限于长时间内可保持的秒数。这比目前估计的宇宙年龄还要大。瞬间存储为纳秒分辨率。
瞬间的范围需要存储大于长时间的数字。为了实现这一点,该类存储一个表示历元秒的长整数和一个表示纳秒的整数,该整数始终在0和999999999之间。历元秒是从1970-01-01T00:00:00Z的标准Java历元开始测量的,其中历元后的瞬间具有正值,较早的瞬间具有负值。对于历元秒和纳秒部分,较大的值总是晚于较小的值。
####时间尺度
太阳日的长度是人类测量时间的标准方式。传统上,这被细分为24小时60分60秒,形成86400秒的一天。
现代计时是以原子钟为基础的,原子钟精确地定义了相对于铯原子跃迁的SI秒。一秒的长度被定义为非常接近一天的86400分之一。
不幸的是,随着地球自转,一天的长度也不尽相同。此外,随着时间的推移,随着地球速度的减慢,一天的平均长度越来越长。因此,2012年的太阳日长度略长于86400 SI秒。任何一天的实际长度以及地球减速的程度都是无法预测的,只能通过测量来确定。UT1时间刻度捕捉到一天的准确长度,但仅在一天结束后的某个时间可用。
UTC时间刻度是一种标准方法,用于将UT1中所有额外的一秒分数捆绑成整秒,称为闰秒。根据地球的自转变化,闰秒可以增加或减少。因此,UTC允许一天有86399 SI秒或86401 SI秒(如有必要),以保持一天与太阳对齐。
现代UTC时标于1972年引入,引入了整闰秒的概念。1958年至1972年期间,UTC的定义非常复杂,有微小的亚秒级跳跃和概念秒长度的改变。截至2012年,有关再次更改UTC定义的讨论正在进行中,可能会删除闰秒或引入其他更改。
鉴于上述精确计时的复杂性,这个JavaAPI通过简化定义了自己的时间尺度。Java时间尺度定义如下:
*中午将始终完全按照商定的国际民用时间来定义
*白天的其他时间将大致与商定的国际民用时间一致
*一天将被精确地划分为86400个部分,称为“秒”
*Java“秒”可能不同于SI秒
约定的国际民用时间是国际公约约定的基准时标,2012年为UTC(闰秒)。
2012年,Java时间刻度的定义与UTC在所有日期的定义相同,但闰秒除外。在发生闰秒的日子里,时间刻度有效地消除了闰秒,保持了一天86400秒的虚构时间。
始终将一天划分为86400个细分的主要好处是,它符合大多数API用户的期望。另一种方法是强迫每个用户理解闰秒是什么,并强迫他们使用特殊的逻辑来处理它们。大多数应用程序无法访问精确到足以记录闰秒的时钟。在闰秒期间,大多数应用程序也不会出现秒比实际SI秒长或短的非常小的问题。
如果应用程序确实可以访问报告闰秒的精确时钟,那么实现Java时间刻度的推荐技术是使用UTC-SLS约定。UTC-SLS有效地平滑了一天中最后1000秒的闰秒,使最后1000“秒”中的每一秒都比实际SI秒长或短1/1000。
最后一个问题是1972年引入现代UTC之前商定的国际民用时间的定义。这包括1970-01-01年的Java时代。其目的是根据划分为86400个细分的太阳日来解释1972年之前的瞬间。
Java时间刻度由所有日期时间类使用。这包括Instant、LocalDate、LocalTime、OffsetDateTime、ZonedDateTime和Duration。
####实施者规范
这个类是不可变的,并且是线程安全的。

代码示例

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

private static void exec(Connection cxn, Migration migration) throws SQLException {
  cxn.setAutoCommit(false);
  try {
    Instant start = Instant.now();
    migration.run(cxn);
    cxn.commit();
    LOGGER.info("Data migration took {} ms", Duration.between(start, Instant.now()).toMillis());
  } catch (SQLException e) {
    LOGGER.error("Data migration failed: {}", e.getMessage(), e);
    cxn.rollback();
    throw e;
  }
}

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

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils {

 public static Date asDate(LocalDate localDate) {
  return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
 }

 public static Date asDate(LocalDateTime localDateTime) {
  return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
 }

 public static LocalDate asLocalDate(Date date) {
  return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
 }

 public static LocalDateTime asLocalDateTime(Date date) {
  return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
 }
}

代码示例来源:origin: oblac/jodd

/**
 * Converts local date time to epoh milliseconds.
 */
public static long toMilliseconds(final LocalDateTime localDateTime) {
  return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}

代码示例来源:origin: thinkaurelius/titan

@Override
  public long getTime(Instant timestamp) {
    return timestamp.getEpochSecond() * 1000000000L + timestamp.getNano();
  }
},

代码示例来源:origin: spring-projects/spring-framework

@Override
public Instant parse(String text, Locale locale) throws ParseException {
  if (text.length() > 0 && Character.isDigit(text.charAt(0))) {
    // assuming UTC instant a la "2007-12-03T10:15:30.00Z"
    return Instant.parse(text);
  }
  else {
    // assuming RFC-1123 value a la "Tue, 3 Jun 2008 11:05:30 GMT"
    return Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(text));
  }
}

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

@JsonValue
@Override
public String toString()
{
  if (isLegacyTimestamp()) {
    return Instant.ofEpochMilli(millis).atZone(ZoneId.of(sessionTimeZoneKey.get().getId())).format(formatter);
  }
  else {
    return Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).format(formatter);
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void shouldHandleLastModifiedWithHttp304() throws Exception {
  long currentTime = new Date().getTime();
  long oneMinuteAgo = currentTime - (1000 * 60);
  ZonedDateTime dateTime = ofEpochMilli(currentTime).atZone(GMT);
  servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, RFC_1123_DATE_TIME.format(dateTime));
  ResponseEntity<String> returnValue = ResponseEntity.ok().lastModified(oneMinuteAgo).body("body");
  initStringMessageConversion(TEXT_PLAIN);
  processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
  assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, null, oneMinuteAgo);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void shouldNotFailPreconditionForPutRequests() throws Exception {
  servletRequest.setMethod("PUT");
  ZonedDateTime dateTime = ofEpochMilli(new Date().getTime()).atZone(GMT);
  servletRequest.addHeader(HttpHeaders.IF_UNMODIFIED_SINCE, RFC_1123_DATE_TIME.format(dateTime));
  long justModified = dateTime.plus(1, ChronoUnit.SECONDS).toEpochSecond() * 1000;
  ResponseEntity<String> returnValue = ResponseEntity.ok()
      .lastModified(justModified).body("body");
  initStringMessageConversion(TEXT_PLAIN);
  processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
  assertConditionalResponse(HttpStatus.OK, null, null, justModified);
}

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

Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDate date = zdt.toLocalDate();

代码示例来源:origin: square/okhttp

/**
 * Add a header with the specified name and formatted instant. Does validation of header names
 * and value.
 */
@IgnoreJRERequirement
public Builder add(String name, Instant value) {
 if (value == null) throw new NullPointerException("value for name " + name + " == null");
 return add(name, new Date(value.toEpochMilli()));
}

代码示例来源:origin: lets-blade/blade

@Before
public void before() {
  time = 1505892010L;
  date = new Date(1505892470110L);
  localDateTime = LocalDateTime.from(Instant.ofEpochSecond(time).atZone(ZoneId.systemDefault()));
}

代码示例来源:origin: chewiebug/GCViewer

public void setModel(GCModel model, GCPreferences preferences) {
  this.model = model;
  if (model.getFirstDateStamp() != null) {
    this.timeOffsetPanel.setDate(new Date(model.getFirstDateStamp().toInstant().toEpochMilli()));
  }
  applyPreferences(preferences);
  setScaleFactor(getScaleFactor());
  setRunningTime(model.getRunningTime());
  setFootprint(model.getFootprint());
  setMaxPause(model.getPause().getMax());
}

代码示例来源:origin: twosigma/beakerx

public static long dateToLong(Object datelike) {
 if (datelike instanceof Date) {
  Date date = (Date) datelike;
  return date.getTime();
 } else if (datelike instanceof Calendar) {
  Calendar calendar = (Calendar) datelike;
  return calendar.getTimeInMillis();
 } else if (datelike instanceof Instant) {
  Instant instant = (Instant) datelike;
  return instant.toEpochMilli();
 } else if (datelike instanceof LocalDateTime) {
  LocalDateTime date = (LocalDateTime) datelike;
  return date.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli();
 } else if (datelike instanceof LocalDate) {
  LocalDate date = (LocalDate) datelike;
  return date.atStartOfDay(ZoneId.of("UTC")).toInstant().toEpochMilli();
 } else {
  throw new IllegalArgumentException("Illegal argument " + datelike
     + ". Expected a Number, Date, Instant, LocalDateTime, or LocalDate");
 }
}

代码示例来源:origin: knowm/XChange

public List<HitbtcOwnTrade> getTradeHistoryRaw(
  String symbol, HitbtcSort sort, Date from, Date till, Integer limit, long offset)
  throws IOException {
 String sortValue = sort != null ? sort.toString().toUpperCase() : null;
 String fromValue = from != null ? Instant.ofEpochMilli(from.getTime()).toString() : null;
 String tillValue = till != null ? Instant.ofEpochMilli(till.getTime()).toString() : null;
 return hitbtc.getHitbtcTrades(
   symbol, sortValue, "timestamp", fromValue, tillValue, limit, offset);
}

代码示例来源:origin: yu199195/hmily

private Object convertDataTypeToDB(final Object params) {
  //https://jdbc.postgresql.org/documentation/head/8-date-time.html
  if (CommonConstant.DB_POSTGRESQL.equals(currentDBType) && params instanceof java.util.Date) {
    return LocalDateTime.ofInstant(Instant.ofEpochMilli(((Date) params).getTime()), ZoneId.systemDefault());
  }
  return params;
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void checkNotModifiedTimestampWithLengthPart() throws Exception {
  long epochTime = dateFormat.parse(CURRENT_TIME).getTime();
  String header = "Wed, 09 Apr 2014 09:57:42 GMT; length=13774";
  MockServerHttpRequest request = get("/").header("If-Modified-Since", header).build();
  MockServerWebExchange exchange = MockServerWebExchange.from(request);
  assertTrue(exchange.checkNotModified(Instant.ofEpochMilli(epochTime)));
  assertEquals(304, exchange.getResponse().getStatusCode().value());
  assertEquals(epochTime, exchange.getResponse().getHeaders().getLastModified());
}

代码示例来源: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: spring-projects/spring-framework

@Test
public void handleReturnValueLastModified() throws Exception {
  Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
  Instant oneMinAgo = currentTime.minusSeconds(60);
  long timestamp = currentTime.toEpochMilli();
  MockServerWebExchange exchange = MockServerWebExchange.from(get("/path").ifModifiedSince(timestamp));
  ResponseEntity<String> entity = ok().lastModified(oneMinAgo.toEpochMilli()).body("body");
  MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
  HandlerResult result = handlerResult(entity, returnType);
  this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
  assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, null, oneMinAgo);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void lastModified() {
  HttpHeaders headers = new HttpHeaders();
  ZonedDateTime lastModified = ZonedDateTime.of(2018, 1, 1, 0, 0, 0, 0, ZoneId.of("UTC"));
  headers.setLastModified(lastModified.toInstant().toEpochMilli());
  HeaderAssertions assertions = headerAssertions(headers);
  assertions.lastModified(lastModified.toInstant().toEpochMilli());
  try {
    assertions.lastModified(lastModified.toInstant().toEpochMilli() + 1);
    fail("Wrong value expected");
  }
  catch (AssertionError error) {
    // Expected
  }
}

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

@Override
@SuppressWarnings("unchecked")
public <X> X unwrap(LocalDate value, Class<X> type, WrapperOptions options) {
  if ( value == null ) {
    return null;
  }
  if ( LocalDate.class.isAssignableFrom( type ) ) {
    return (X) value;
  }
  if ( java.sql.Date.class.isAssignableFrom( type ) ) {
    return (X) java.sql.Date.valueOf( value );
  }
  final LocalDateTime localDateTime = value.atStartOfDay();
  if ( Timestamp.class.isAssignableFrom( type ) ) {
    return (X) Timestamp.valueOf( localDateTime );
  }
  final ZonedDateTime zonedDateTime = localDateTime.atZone( ZoneId.systemDefault() );
  if ( Calendar.class.isAssignableFrom( type ) ) {
    return (X) GregorianCalendar.from( zonedDateTime );
  }
  final Instant instant = zonedDateTime.toInstant();
  if ( Date.class.equals( type ) ) {
    return (X) Date.from( instant );
  }
  if ( Long.class.isAssignableFrom( type ) ) {
    return (X) Long.valueOf( instant.toEpochMilli() );
  }
  throw unknownUnwrap( type );
}

相关文章