下面列出了org.junit.jupiter.api.DisplayName#java.time.ZonedDateTime 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void test_Apia_jumpForwardOverInternationalDateLine_P12_to_M12() {
// transition occurred at 1879-07-04T00:00+12:33:04
ZoneRules test = pacificApia();
Instant instantBefore = LocalDate.of(1879, 7, 2).atStartOfDay(ZoneOffset.UTC).toInstant();
ZoneOffsetTransition trans = test.nextTransition(instantBefore);
assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(1879, 7, 5, 0, 0));
assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(1879, 7, 4, 0, 0));
assertEquals(trans.isGap(), false);
assertEquals(trans.isOverlap(), true);
assertEquals(trans.isValidOffset(ZoneOffset.ofHoursMinutesSeconds(+12, 33, 4)), true);
assertEquals(trans.isValidOffset(ZoneOffset.ofHoursMinutesSeconds(-11, -26, -56)), true);
assertEquals(trans.getDuration(), Duration.ofHours(-24));
assertEquals(trans.getInstant(), LocalDateTime.of(1879, 7, 4, 0, 0).toInstant(ZoneOffset.ofHoursMinutesSeconds(-11, -26, -56)));
ZonedDateTime zdt = ZonedDateTime.of(1879, 7, 4, 23, 0, 0, 0, ZoneId.of("Pacific/Apia"));
assertEquals(zdt.plusHours(2).toLocalDateTime(), LocalDateTime.of(1879, 7, 4, 1, 0, 0));
}
@Test
public void constructor_has_guard_clause_for_null_occurrenceTime() {
// Arrange
ZonedDateTime occurrenceTime = null;
// Act
IllegalArgumentException expected = null;
try {
new IssueCreatedForTesting(UUID.randomUUID(), 1, occurrenceTime);
} catch (IllegalArgumentException e) {
expected = e;
}
// Assert
Assert.assertNotNull(expected);
Assert.assertTrue(
"The error message should contain the name of the parameter 'occurrenceTime'.",
expected.getMessage().contains("'occurrenceTime'"));
}
public Optional<String> getFormatedNextRunTime() {
Optional<Long> msToNextRun = getMillisecondsToNextRun();
if (msToNextRun.isPresent()) {
ZonedDateTime currentUTCTime = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime nextRunTime = currentUTCTime.plus(msToNextRun.get(), ChronoUnit.MILLIS);
int seconds = nextRunTime.getSecond();
if (seconds >= 30) {
nextRunTime = nextRunTime.truncatedTo(ChronoUnit.MINUTES).plusMinutes(1);
} else {
nextRunTime = nextRunTime.truncatedTo(ChronoUnit.MINUTES);
}
String formattedString = nextRunTime.format(DateTimeFormatter.ofPattern(FORMAT_PATTERN));
return Optional.of(formattedString + " UTC");
}
return Optional.empty();
}
private static Optional<ZonedDateTime> dateTimeFromTemporal( TemporalAccessor ta ) {
ToIntBiFunction<ChronoField, Integer> getField = ( field, orElse ) ->
ta.isSupported( field ) ? ta.get( field ) : orElse;
ZoneId zone = Optional.<ZoneId>ofNullable( ta.query( offset() ) )
.orElse( Optional.ofNullable( ta.query( zoneId() ) )
.orElse( ZoneOffset.UTC ) );
int year = getField.applyAsInt( ChronoField.YEAR, THIS_YEAR );
int month = getField.applyAsInt( ChronoField.MONTH_OF_YEAR, 1 );
int day = getField.applyAsInt( ChronoField.DAY_OF_MONTH, 1 );
int hour = getField.applyAsInt( ChronoField.HOUR_OF_DAY, 0 );
int minute = getField.applyAsInt( ChronoField.MINUTE_OF_HOUR, 0 );
int second = getField.applyAsInt( ChronoField.SECOND_OF_MINUTE, 0 );
int nanos = getField.applyAsInt( ChronoField.NANO_OF_SECOND, 0 );
ZonedDateTime dateTime = ZonedDateTime.of( year, month, day, hour, minute, second, nanos, zone );
return Optional.of( dateTime );
}
@Test
public void now_Clock_allSecsInDay_utc() {
for (int i = 0; i < (2 * 24 * 60 * 60); i++) {
Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L);
Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
ZonedDateTime test = ZonedDateTime.now(clock);
assertEquals(test.getYear(), 1970);
assertEquals(test.getMonth(), Month.JANUARY);
assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60 ? 1 : 2));
assertEquals(test.getHour(), (i / (60 * 60)) % 24);
assertEquals(test.getMinute(), (i / 60) % 60);
assertEquals(test.getSecond(), i % 60);
assertEquals(test.getNano(), 123456789);
assertEquals(test.getOffset(), ZoneOffset.UTC);
assertEquals(test.getZone(), ZoneOffset.UTC);
}
}
@Test
public void test_notBeforeThrows() {
JWT expectedJWT = new JWT()
.setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60).truncatedTo(ChronoUnit.SECONDS))
.setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS))
.setIssuer("www.inversoft.com")
.setNotBefore(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(5).truncatedTo(ChronoUnit.SECONDS));
Signer signer = HMACSigner.newSHA256Signer("secret");
Verifier verifier = HMACVerifier.newVerifier("secret");
String encodedJWT = JWT.getEncoder().encode(expectedJWT, signer);
expectException(JWTUnavailableForProcessingException.class, ()
-> JWT.getDecoder().decode(encodedJWT, verifier));
}
@Override
public State calculate(Set<Item> items) {
if (items != null && items.size() > 0) {
ZonedDateTime max = null;
for (Item item : items) {
DateTimeType itemState = item.getStateAs(DateTimeType.class);
if (itemState != null) {
if (max == null || max.isBefore(itemState.getZonedDateTime())) {
max = itemState.getZonedDateTime();
}
}
}
if (max != null) {
return new DateTimeType(max);
}
}
return UnDefType.UNDEF;
}
@Test
public void test_with_adjuster_OffsetDateTime_retainOffsetInOverlap2() {
// ODT will be a valid ZDT for the zone, so must be retained exactly
OffsetDateTime odt = TEST_PARIS_OVERLAP_2008_10_26_02_30.atOffset(OFFSET_0200);
ZonedDateTime zdt = TEST_LOCAL_2008_06_30_11_30_59_500.atZone(ZONE_PARIS);
ZonedDateTime test = zdt.with(odt);
assertEquals(test.toOffsetDateTime(), odt);
}
@Test
public void test_withEarlierOffsetAtOverlap_atOverlap() {
ZonedDateTime base = ZonedDateTime.ofStrict(TEST_PARIS_OVERLAP_2008_10_26_02_30, OFFSET_0100, ZONE_PARIS);
ZonedDateTime test = base.withEarlierOffsetAtOverlap();
assertEquals(test.getOffset(), OFFSET_0200); // offset changed to earlier
assertEquals(test.toLocalDateTime(), base.toLocalDateTime()); // date-time not changed
}
private static Commit commit(Hash hash, List<String> message, List<Diff> parentDiffs) {
var author = new Author("Foo Bar", "[email protected]");
var parents = List.of(new Hash("12345789012345789012345678901234567890"));
var authored = ZonedDateTime.now();
var metadata = new CommitMetadata(hash, parents, author, authored, author, authored, message);
return new Commit(metadata, parentDiffs);
}
@Test
@UseDataProvider("data_of_calendars")
public void test_ChronoZonedDateTimeSerialization(Chronology chrono) throws Exception {
ZonedDateTime ref = LocalDate.of(2013, 1, 5).atTime(12, 1, 2, 3).atZone(ZoneId.of("GMT+01:23"));
ChronoZonedDateTime<?> original = chrono.date(ref).atTime(ref.toLocalTime()).atZone(ref.getZone());
assertSerializable(original);
}
@Query("insert into b_transaction(gtw_tx_id, gtw_payment_id, reservation_id, t_timestamp, price_cts, currency, description, payment_proxy, plat_fee, gtw_fee, status, metadata) " +
"values(:transactionId, :paymentId, :reservationId, :timestamp, :priceInCents, :currency, :description, :paymentProxy, :platformFee, :gatewayFee, :status, to_json(:metadata::json))")
int insert(@Bind("transactionId") String transactionId,
@Bind("paymentId") String paymentId,
@Bind("reservationId") String reservationId,
@Bind("timestamp") ZonedDateTime timestamp,
@Bind("priceInCents") int priceInCents,
@Bind("currency") String currency,
@Bind("description") String description,
@Bind("paymentProxy") String paymentProxy,
@Bind("platformFee") long platformFee,
@Bind("gatewayFee") long gatewayFee,
@Bind("status") Transaction.Status status,
@Bind("metadata") @JSONData Map<String, String> metadata);
@Test
public void test_compareTo_offset2() {
ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, 11, 30, 40, 5, ZoneId.of("UTC+01:01"));
ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, 11, 30, 40, 4, ZONE_0100); // a is before b due to offset
assertEquals(a.compareTo(b) < 0, true);
assertEquals(b.compareTo(a) > 0, true);
assertEquals(a.compareTo(a) == 0, true);
assertEquals(b.compareTo(b) == 0, true);
}
@Test
public void givenLocalDateTime_WhenToEpochMillis_ThenMillis() {
ZoneId id = ZoneId.systemDefault();
LocalDateTime localDateTime =
LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(millis), id);
ZonedDateTime zdt = ZonedDateTime.of(localDateTime, id);
Assert.assertEquals(millis, zdt.toInstant().toEpochMilli());
}
@Override
public ZonedDateTime getActivationDateForActiveScript(Username username) throws ScriptNotFoundException {
return cassandraActiveScriptDAO.getActiveSctiptInfo(username)
.blockOptional()
.orElseThrow(ScriptNotFoundException::new)
.getActivationDate();
}
@Test
public void test_plusYears() {
LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0);
ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100);
ZonedDateTime test = base.plusYears(1);
assertEquals(test, ZonedDateTime.of(ldt.plusYears(1), ZONE_0100));
}
@Test(expectedExceptions=DateTimeParseException.class)
public void test_parseBest_String_parseError() throws Exception {
DateTimeFormatter test = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm[XXX]");
try {
test.parseBest("2011-06-XX", ZonedDateTime::from, LocalDateTime::from);
} catch (DateTimeParseException ex) {
assertEquals(ex.getMessage().contains("could not be parsed"), true);
assertEquals(ex.getMessage().contains("XX"), true);
assertEquals(ex.getParsedString(), "2011-06-XX");
assertEquals(ex.getErrorIndex(), 8);
throw ex;
}
}
@Test
void neverReturnADateInThePast() {
initOfflinePaymentTest();
when(event.getBegin()).thenReturn(ZonedDateTime.now());
ZonedDateTime offlinePaymentDeadline = BankTransferManager.getOfflinePaymentDeadline(new PaymentContext(event), configurationManager);
assertTrue(offlinePaymentDeadline.isAfter(ZonedDateTime.now()));
}
@Test
public void parseDates() {
ContentDisposition disposition = ContentDisposition
.parse("attachment; creation-date=\"Mon, 12 Feb 2007 10:15:30 -0500\"; " +
"modification-date=\"Tue, 13 Feb 2007 10:15:30 -0500\"; " +
"read-date=\"Wed, 14 Feb 2007 10:15:30 -0500\"");
DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
assertEquals(ContentDisposition.builder("attachment")
.creationDate(ZonedDateTime.parse("Mon, 12 Feb 2007 10:15:30 -0500", formatter))
.modificationDate(ZonedDateTime.parse("Tue, 13 Feb 2007 10:15:30 -0500", formatter))
.readDate(ZonedDateTime.parse("Wed, 14 Feb 2007 10:15:30 -0500", formatter)).build(), disposition);
}
@Test
public void ppPyDate() {
assertThat(
f.filter(
new PyishDate(ZonedDateTime.of(2014, 8, 4, 0, 0, 0, 0, ZoneOffset.UTC)),
null
)
)
.isEqualTo("{% raw %}(PyishDate: 2014-08-04 00:00:00){% endraw %}");
}
@Test
public void test_plusYears() {
LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0);
ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100);
ZonedDateTime test = base.plusYears(1);
assertEquals(test, ZonedDateTime.of(ldt.plusYears(1), ZONE_0100));
}
@Query("insert into additional_service (event_id_fk, fix_price, ordinal, available_qty, max_qty_per_order, inception_ts, expiration_ts, vat, vat_type, price_cts, src_price_cts, service_type, supplement_policy) " +
"values(:eventId, :fixPrice, :ordinal, :availableQty, :maxQtyPerOrder, :inceptionTs, :expirationTs, :vat, :vatType, 0, :srcPriceCts, :type, :supplementPolicy)")
@AutoGeneratedKey("id")
AffectedRowCountAndKey<Integer> insert(@Bind("eventId") int eventId, @Bind("srcPriceCts") int srcPriceCts, @Bind("fixPrice") boolean fixPrice,
@Bind("ordinal") int ordinal, @Bind("availableQty") int availableQuantity, @Bind("maxQtyPerOrder") int maxQtyPerOrder,
@Bind("inceptionTs") ZonedDateTime inception, @Bind("expirationTs") ZonedDateTime expiration, @Bind("vat") BigDecimal vat,
@Bind("vatType") AdditionalService.VatType vatType,
@Bind("type")AdditionalService.AdditionalServiceType type,
@Bind("supplementPolicy") AdditionalService.SupplementPolicy supplementPolicy);
@Test
public void test_parse_errorMessage() throws Exception {
assertGoodErrorDate(DayOfWeek::from, "DayOfWeek");
assertGoodErrorDate(Month::from, "Month");
assertGoodErrorDate(YearMonth::from, "YearMonth");
assertGoodErrorDate(MonthDay::from, "MonthDay");
assertGoodErrorDate(LocalDate::from, "LocalDate");
assertGoodErrorDate(LocalTime::from, "LocalTime");
assertGoodErrorDate(LocalDateTime::from, "LocalDateTime");
assertGoodErrorDate(OffsetTime::from, "OffsetTime");
assertGoodErrorDate(OffsetDateTime::from, "OffsetDateTime");
assertGoodErrorDate(ZonedDateTime::from, "ZonedDateTime");
assertGoodErrorDate(Instant::from, "Instant");
assertGoodErrorDate(ZoneOffset::from, "ZoneOffset");
assertGoodErrorDate(ZoneId::from, "ZoneId");
assertGoodErrorDate(ThaiBuddhistChronology.INSTANCE::date, "");
assertGoodErrorTime(DayOfWeek::from, "DayOfWeek");
assertGoodErrorTime(Month::from, "Month");
assertGoodErrorTime(Year::from, "Year");
assertGoodErrorTime(YearMonth::from, "YearMonth");
assertGoodErrorTime(MonthDay::from, "MonthDay");
assertGoodErrorTime(LocalDate::from, "LocalDate");
assertGoodErrorTime(LocalTime::from, "LocalTime");
assertGoodErrorTime(LocalDateTime::from, "LocalDateTime");
assertGoodErrorTime(OffsetTime::from, "OffsetTime");
assertGoodErrorTime(OffsetDateTime::from, "OffsetDateTime");
assertGoodErrorTime(ZonedDateTime::from, "ZonedDateTime");
assertGoodErrorTime(Instant::from, "Instant");
assertGoodErrorTime(ZoneOffset::from, "ZoneOffset");
assertGoodErrorTime(ZoneId::from, "ZoneId");
assertGoodErrorTime(ThaiBuddhistChronology.INSTANCE::date, "");
}
@Test(dataProvider="print")
public void test_print_pattern_x(String offsetPattern, String noOffset, LocalDateTime ldt, ZoneId zone, String expected) {
String pattern = null;
String zero = null;
if (offsetPattern.equals("+HHmm") && noOffset.equals("Z")) {
pattern = "x";
zero = "+00";
} else if (offsetPattern.equals("+HHMM") && noOffset.equals("Z")) {
pattern = "xx";
zero = "+0000";
} else if (offsetPattern.equals("+HH:MM") && noOffset.equals("Z")) {
pattern = "xxx";
zero = "+00:00";
} else if (offsetPattern.equals("+HHMMss") && noOffset.equals("Z")) {
pattern = "xxxx";
zero = "+0000";
} else if (offsetPattern.equals("+HH:MM:ss") && noOffset.equals("Z")) {
pattern = "xxxxx";
zero = "+00:00";
}
if (pattern != null) {
ZonedDateTime zdt = ldt.atZone(zone);
builder.appendPattern(pattern);
String output = builder.toFormatter().format(zdt);
assertEquals(output, (expected.equals("Z") ? zero : expected));
}
}
@Test(dataProvider="print_localized")
public void test_print_localized(TextStyle style, LocalDateTime ldt, ZoneOffset offset, String expected) {
OffsetDateTime odt = OffsetDateTime.of(ldt, offset);
ZonedDateTime zdt = ldt.atZone(offset);
DateTimeFormatter f = new DateTimeFormatterBuilder().appendLocalizedOffset(style)
.toFormatter();
assertEquals(f.format(odt), expected);
assertEquals(f.format(zdt), expected);
assertEquals(f.parse(expected, ZoneOffset::from), offset);
if (style == TextStyle.FULL) {
f = new DateTimeFormatterBuilder().appendPattern("ZZZZ")
.toFormatter();
assertEquals(f.format(odt), expected);
assertEquals(f.format(zdt), expected);
assertEquals(f.parse(expected, ZoneOffset::from), offset);
f = new DateTimeFormatterBuilder().appendPattern("OOOO")
.toFormatter();
assertEquals(f.format(odt), expected);
assertEquals(f.format(zdt), expected);
assertEquals(f.parse(expected, ZoneOffset::from), offset);
}
if (style == TextStyle.SHORT) {
f = new DateTimeFormatterBuilder().appendPattern("O")
.toFormatter();
assertEquals(f.format(odt), expected);
assertEquals(f.format(zdt), expected);
assertEquals(f.parse(expected, ZoneOffset::from), offset);
}
}
static ZonedDateTime read(BsonReader reader, String field) {
BsonType currentType = reader.getCurrentBsonType();
if (currentType == BsonType.NULL) {
reader.readNull();
return null;
} else if (currentType == BsonType.DATE_TIME) {
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(reader.readDateTime()), ZoneId.systemDefault());
} else {
LOGGER.warn("unexpected field type, field={}, type={}", field, currentType);
reader.skipValue();
return null;
}
}
@FXML
void initialize() {
try {
this.update();
// マウスオーバーでのポップアップ
PopOver<DeckPort> popover = new PopOver<>((node, port) -> {
String message;
// 帰還時間
long time = this.port.getMission().get(2);
if (time > 0) {
ZonedDateTime dateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(time),
ZoneOffset.systemDefault());
if (dateTime.toLocalDate().equals(ZonedDateTime.now().toLocalDate())) {
message = "今日 " + DateTimeFormatter.ofPattern("H時m分s秒").format(dateTime)
+ " 頃に帰投します";
} else {
message = DateTimeFormatter.ofPattern("M月d日 H時m分s秒").format(dateTime)
+ " 頃に帰投します";
}
} else {
message = "任務がありません";
}
return new PopOverPane(port.getName(), message);
});
popover.install(this, this.port);
} catch (Exception e) {
LoggerHolder.get().error("FXMLの初期化に失敗しました", e);
}
}
@Test(dataProvider="plusDays")
public void test_until_days(ZonedDateTime base, long expected, ZonedDateTime end) {
if (base.toLocalTime().equals(end.toLocalTime()) == false) {
return; // avoid DST gap input values
}
assertEquals(base.until(end, DAYS), expected);
}
@Test
public void test_plusYears_zero() {
LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0);
ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100);
ZonedDateTime test = base.plusYears(0);
assertEquals(test, base);
}
@Test
public void test_minusSeconds_seconds() {
LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0);
ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100);
ZonedDateTime test = base.minusSeconds(1);
assertEquals(test, ZonedDateTime.of(ldt.minusSeconds(1), ZONE_0100));
}