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

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

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

Instant介绍

[英]Instant is the standard implementation of a fully immutable instant in time.

Instant is an implementation of ReadableInstant. As with all instants, it represents an exact point on the time-line, but limited to the precision of milliseconds. An Instant should be used to represent a point in time irrespective of any other factor, such as chronology or time zone.

Internally, the class holds one piece of data, the instant as milliseconds from the Java epoch of 1970-01-01T00:00:00Z.

For example, an Instant can be used to compare two DateTime objects irrespective of chronology or time zone.

boolean sameInstant = dt1.toInstant().equals(dt2.toInstant());

Note that the following code will also perform the same check:

boolean sameInstant = dt1.isEqual(dt2);

Instant is thread-safe and immutable.
[中]Instant是时间上完全不变的Instant的标准实现。
Instant是ReadableInstant的一个实现。与所有实例一样,它表示时间线上的精确点,但精度仅限于毫秒。应使用Instant来表示时间点,而不考虑任何其他因素,如时间顺序或时区。
在内部,该类保存一段数据,即从1970-01-01T00:00:00Z的Java纪元开始的毫秒数。
例如,可以使用一个瞬间来比较两个DateTime对象,而不考虑时间顺序或时区。

boolean sameInstant = dt1.toInstant().equals(dt2.toInstant());

请注意,以下代码也将执行相同的检查:

boolean sameInstant = dt1.isEqual(dt2);

Instant是线程安全且不可变的。

代码示例

代码示例来源:origin: joda-time/joda-time

/**
 * Obtains an {@code Instant} set to the milliseconds from 1970-01-01T00:00:00Z.
 * 
 * @param epochMilli  the milliseconds from 1970-01-01T00:00:00Z
 * @since 2.10
 */
public static Instant ofEpochMilli(long epochMilli) {
  return new Instant(epochMilli);
}

代码示例来源:origin: stanfordnlp/CoreNLP

public static Time closest(Time ref, Time... times) {
 Time res = null;
 long refMillis = ref.getJodaTimeInstant().getMillis();
 long min = 0;
 for (Time t:times) {
  long d = Math.abs(refMillis - t.getJodaTimeInstant().getMillis());
  if (res == null || d < min) {
   res = t;
   min = d;
  }
 }
 return res;
}

代码示例来源:origin: joda-time/joda-time

/**
 * Get this object as a DateTime using ISOChronology in the default zone.
 * This method is identical to <code>toDateTime()</code>.
 * <p>
 * This method returns a DateTime object in the default zone.
 * This differs from the similarly named method on DateTime, DateMidnight
 * or MutableDateTime which retains the time zone. The difference is
 * because Instant really represents a time <i>without</i> a zone,
 * thus calling this method we really have no zone to 'retain' and
 * hence expect to switch to the default zone.
 * <p>
 * This method is deprecated because it is a duplicate of {@link #toDateTime()}.
 * However, removing it would cause the superclass implementation to be used,
 * which would create silent bugs in any caller depending on this implementation.
 * As such, the method itself is not currently planned to be removed.
 * <p>
 * This method definition preserves compatibility with earlier versions
 * of Joda-Time.
 *
 * @return a DateTime using the same millis with ISOChronology
 * @deprecated Use toDateTime() as it is identical
 */
@Deprecated
public DateTime toDateTimeISO() {
  return toDateTime();
}

代码示例来源:origin: joda-time/joda-time

/**
 * Gets a copy of this instant with the specified duration added.
 * <p>
 * If the addition is zero, then <code>this</code> is returned.
 * 
 * @param durationToAdd  the duration to add to this one
 * @param scalar  the amount of times to add, such as -1 to subtract once
 * @return a copy of this instant with the duration added
 * @throws ArithmeticException if the new instant exceeds the capacity of a long
 */
public Instant withDurationAdded(long durationToAdd, int scalar) {
  if (durationToAdd == 0 || scalar == 0) {
    return this;
  }
  long instant = getChronology().add(getMillis(), durationToAdd, scalar);
  return withMillis(instant);
}

代码示例来源:origin: alibaba/fastjson

Duration duration = Duration.parse(text);
Instant instant = Instant.parse(text);
Instant instant = new Instant(millis);

代码示例来源:origin: rackerlabs/blueflood

@Test
public void perTenantMetricsOff_shouldNotRecordMetrics() throws Exception {
  long timestamp = new DefaultClockImpl().now().getMillis();
  FullHttpRequest request = createIngestRequest(
      getJsonFromFile("sample_multi_aggregated_payload.json", timestamp, postfix));
  long ingestedMetricsBefore = ingestedMetrics.getCount();
  long ingestedDelayedMetricsBefore = ingestedDelayedMetrics.getCount();
  ListenableFuture<List<Boolean>> futures = mock(ListenableFuture.class);
  List<Boolean> answers = new ArrayList<>();
  answers.add(Boolean.TRUE);
  when(processor.apply(any())).thenReturn(futures);
  when(futures.get(anyLong(), any())).thenReturn(answers);
  // turn off per tenant metrics tracking
  HttpAggregatedMultiIngestionHandler handler = spy(new HttpAggregatedMultiIngestionHandler(processor, new TimeValue(5, TimeUnit.SECONDS), false));
  ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
  handler.handle(context, request);
  verify(channel).write(argument.capture());
  verify(handler, times(1)).recordPerTenantMetrics(eq(TENANT), eq(12), eq(0));
  assertEquals("ingested metrics count", 0, ingestedMetrics.getCount() - ingestedMetricsBefore);
  assertEquals("ingested delayed metrics count", 0, ingestedDelayedMetrics.getCount() - ingestedDelayedMetricsBefore);
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

/** Tests that the watermark that guarantees firing is that of the subtrigger. */
@Test
public void testFireDeadline() throws Exception {
 setUp(FixedWindows.of(Duration.millis(10)));
 IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10));
 Instant arbitraryInstant = new Instant(34957849);
 when(mockTrigger.getWatermarkThatGuaranteesFiring(Mockito.<IntervalWindow>any()))
   .thenReturn(arbitraryInstant);
 assertThat(
   Repeatedly.forever(mockTrigger).getWatermarkThatGuaranteesFiring(window),
   equalTo(arbitraryInstant));
}

代码示例来源:origin: org.apache.beam/beam-runners-direct-java

@Test
public void getSynchronizedProcessingTimeIsWatermarkSynchronizedInputTime() {
 when(watermarks.getSynchronizedProcessingInputTime()).thenReturn(new Instant(12345L));
 assertThat(internals.currentSynchronizedProcessingTime(), equalTo(new Instant(12345L)));
}

代码示例来源:origin: rackerlabs/blueflood

@Test
public void testValidTimer() throws IOException {
  BluefloodTimer timer = new BluefloodTimer("timer.a.b", 5);
  FullHttpRequest request = createIngestRequest(createRequestBody(TENANT,
      new DefaultClockImpl().now().getMillis(), 0, null, null, new BluefloodTimer[]{timer}, null));
  ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
  handler.handle(context, request);
  verify(channel).write(argument.capture());
  String responseBody = argument.getValue().content().toString(Charset.defaultCharset());
  assertEquals("Invalid response", "", responseBody);
  assertEquals("Invalid status", HttpResponseStatus.OK, argument.getValue().getStatus());
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-io-kinesis

@Before
public void setUp() throws TransientKinesisException {
 when(generator.generate(kinesis))
   .thenReturn(new KinesisReaderCheckpoint(asList(firstCheckpoint, secondCheckpoint)));
 when(shardReadersPool.nextRecord()).thenReturn(CustomOptional.absent());
 when(a.getApproximateArrivalTimestamp()).thenReturn(Instant.now());
 when(b.getApproximateArrivalTimestamp()).thenReturn(Instant.now());
 when(c.getApproximateArrivalTimestamp()).thenReturn(Instant.now());
 when(d.getApproximateArrivalTimestamp()).thenReturn(Instant.now());
 reader = createReader(Duration.ZERO);
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

@ProcessElement
 public void processElement(ProcessContext c) throws Exception {
  assertThat(
    c.timestamp(),
    equalTo(
      new IntervalWindow(
          new Instant(0),
          new Instant(0).plus(Duration.standardMinutes(10)))
        .maxTimestamp()));
 }
}));

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

@Test
public void testSlightlyOverlapping() throws Exception {
 Map<IntervalWindow, Set<String>> expected = new HashMap<>();
 expected.put(new IntervalWindow(new Instant(-5), new Instant(2)), set(1));
 expected.put(new IntervalWindow(new Instant(0), new Instant(7)), set(1, 2, 5));
 expected.put(new IntervalWindow(new Instant(5), new Instant(12)), set(5, 9, 10, 11));
 expected.put(new IntervalWindow(new Instant(10), new Instant(17)), set(10, 11));
 SlidingWindows windowFn = SlidingWindows.of(new Duration(7)).every(new Duration(5));
 assertEquals(expected, runWindowFn(windowFn, Arrays.asList(1L, 2L, 5L, 9L, 10L, 11L)));
 assertThat(windowFn.assignsToOneWindow(), is(false));
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

@Test
@Category(NeedsRunner.class)
public void testUnboundedInputRate() {
 long numElements = 5000;
 long elemsPerPeriod = 10L;
 Duration periodLength = Duration.millis(8);
 PCollection<Long> input =
   p.apply(GenerateSequence.from(0).to(numElements).withRate(elemsPerPeriod, periodLength));
 addCountingAsserts(input, 0, numElements);
 long expectedRuntimeMillis = (periodLength.getMillis() * numElements) / elemsPerPeriod;
 Instant startTime = Instant.now();
 p.run();
 Instant endTime = Instant.now();
 assertThat(endTime.isAfter(startTime.plus(expectedRuntimeMillis)), is(true));
}

代码示例来源:origin: org.apache.beam/beam-runners-core-java

@Test
public void testTimerForEndOfWindowCompound() throws Exception {
 tester =
   TriggerStateMachineTester.forTrigger(
     AfterWatermarkStateMachine.pastEndOfWindow().withEarlyFirings(NeverStateMachine.ever()),
     FixedWindows.of(Duration.millis(100)));
 assertThat(tester.getNextTimer(TimeDomain.EVENT_TIME), nullValue());
 injectElements(1);
 IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(100));
 assertThat(tester.getNextTimer(TimeDomain.EVENT_TIME), equalTo(window.maxTimestamp()));
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

@Test
@Category(NeedsRunner.class)
public void testCreateParameterizedType() throws Exception {
 PCollection<TimestampedValue<String>> output =
   p.apply(
     Create.of(
       TimestampedValue.of("a", new Instant(0)),
       TimestampedValue.of("b", new Instant(0))));
 PAssert.that(output)
   .containsInAnyOrder(
     TimestampedValue.of("a", new Instant(0)), TimestampedValue.of("b", new Instant(0)));
 p.run();
}
/** An unserializable class to demonstrate encoding of elements. */

代码示例来源:origin: org.apache.beam/beam-runners-direct-java

@Test
public void getProcessingTimeIsClockNow() {
 assertThat(internals.currentProcessingTime(), equalTo(clock.now()));
 Instant oldProcessingTime = internals.currentProcessingTime();
 clock.advance(Duration.standardHours(12));
 assertThat(internals.currentProcessingTime(), equalTo(clock.now()));
 assertThat(
   internals.currentProcessingTime(),
   equalTo(oldProcessingTime.plus(Duration.standardHours(12))));
}

代码示例来源:origin: org.apache.beam/beam-runners-core-java

@Test
 public void falseAfterEndOfWindow() throws Exception {
  triggerTester.injectElements(TimestampedValue.of(1, new Instant(1)));
  IntervalWindow window =
    new IntervalWindow(new Instant(0), new Instant(0).plus(Duration.standardMinutes(5)));
  assertThat(triggerTester.shouldFire(window), is(false));
  triggerTester.advanceInputWatermark(BoundedWindow.TIMESTAMP_MAX_VALUE);
  assertThat(triggerTester.shouldFire(window), is(false));
 }
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

@Test
public void testExplodeWindowsInOneWindowEquals() {
 Instant now = Instant.now();
 BoundedWindow window = new IntervalWindow(now.minus(1000L), now.plus(1000L));
 WindowedValue<String> value =
   WindowedValue.of("foo", now, window, PaneInfo.ON_TIME_AND_ONLY_FIRING);
 assertThat(Iterables.getOnlyElement(value.explodeWindows()), equalTo(value));
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

@Test
@Category(NeedsRunner.class)
public void testSampleAnyInsufficientElements() {
 PCollection<Integer> input = pipeline.apply(Create.empty(BigEndianIntegerCoder.of()));
 PCollection<Integer> output =
   input
     .apply(Window.into(FixedWindows.of(Duration.standardSeconds(3))))
     .apply(Sample.any(10));
 PAssert.that(output)
   .inWindow(new IntervalWindow(new Instant(0), Duration.standardSeconds(3)))
   .satisfies(new VerifyCorrectSample<>(0, EMPTY));
 pipeline.run();
}

代码示例来源:origin: org.apache.beam/beam-runners-direct-java

@Test
public void createKeyedBundleKeyed() {
 StructuralKey<String> key = StructuralKey.of("foo", StringUtf8Coder.of());
 CommittedBundle<KV<String, Integer>> keyedBundle =
   context.createKeyedBundle(key, downstream).commit(Instant.now());
 assertThat(keyedBundle.getKey(), equalTo(key));
}

相关文章