java.time.ZonedDateTime Java Examples

The following examples show how to use java.time.ZonedDateTime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JWTTest.java    From fusionauth-jwt with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #2
Source File: TCKZonedDateTime.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@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);
    }
}
 
Example #3
Source File: DateTimeFormatGuesser.java    From LogFX with GNU General Public License v3.0 6 votes vote down vote up
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 );
}
 
Example #4
Source File: ScheduledTask.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #5
Source File: AbstractDomainEventSpecs.java    From loom with MIT License 6 votes vote down vote up
@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'"));
}
 
Example #6
Source File: TCKZoneRules.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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));
}
 
Example #7
Source File: DateTimeGroupFunction.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: PrettyPrintFilterTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@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 %}");
}
 
Example #9
Source File: CassandraSieveRepository.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public ZonedDateTime getActivationDateForActiveScript(Username username) throws ScriptNotFoundException {
    return cassandraActiveScriptDAO.getActiveSctiptInfo(username)
        .blockOptional()
        .orElseThrow(ScriptNotFoundException::new)
        .getActivationDate();
}
 
Example #10
Source File: TCKZonedDateTime.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #11
Source File: ContentDispositionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #12
Source File: TCKZonedDateTime.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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));
}
 
Example #13
Source File: EventManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public void updatePromoCode(int promoCodeId, ZonedDateTime start, ZonedDateTime end, Integer maxUsage, List<Integer> categories, String description, String emailReference, Integer hiddenCategoryId) {
    Validate.isTrue(StringUtils.length(description) < 1025, "Description can be maximum 1024 chars");
    Validate.isTrue(StringUtils.length(emailReference) < 257, "Description can be maximum 256 chars");
    String categoriesJson = CollectionUtils.isEmpty(categories) ? null : Json.toJson(categories);

    promoCodeRepository.updateEventPromoCode(promoCodeId, start, end, maxUsage, categoriesJson, description, emailReference, hiddenCategoryId);
}
 
Example #14
Source File: TicketReservationManagerTest.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Test
void neverReturnADateInThePast() {
    initOfflinePaymentTest();
    when(event.getBegin()).thenReturn(ZonedDateTime.now());
    ZonedDateTime offlinePaymentDeadline = BankTransferManager.getOfflinePaymentDeadline(new PaymentContext(event), configurationManager);
    assertTrue(offlinePaymentDeadline.isAfter(ZonedDateTime.now()));
}
 
Example #15
Source File: TCKDateTimeFormatter.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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;
    }
}
 
Example #16
Source File: ConvertDateTimeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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());
}
 
Example #17
Source File: TCKChronoZonedDateTimeSerialization.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: TransactionRepository.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@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);
 
Example #19
Source File: ClientSideRequestStatistics.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult) {
    ZonedDateTime responseTime = ZonedDateTime.now(ZoneOffset.UTC);

    StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics();
    storeResponseStatistics.requestResponseTime = responseTime;
    storeResponseStatistics.storeResult = storeResult;
    storeResponseStatistics.requestOperationType = request.getOperationType();
    storeResponseStatistics.requestResourceType = request.getResourceType();

    URI locationEndPoint = null;
    if (request.requestContext.locationEndpointToRoute != null) {
        try {
            locationEndPoint = request.requestContext.locationEndpointToRoute.toURI();
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
    }

    synchronized (this) {
        if (responseTime.isAfter(this.requestEndTime)) {
            this.requestEndTime = responseTime;
        }

        if (locationEndPoint != null) {
            this.regionsContacted.add(locationEndPoint);
        }

        if (storeResponseStatistics.requestOperationType == OperationType.Head ||
                storeResponseStatistics.requestOperationType == OperationType.HeadFeed) {
            this.supplementalResponseStatisticsList.add(storeResponseStatistics);
        } else {
            this.responseStatisticsList.add(storeResponseStatistics);
        }
    }
}
 
Example #20
Source File: TCKZonedDateTime.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #21
Source File: TCKZonedDateTime.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@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));
}
 
Example #22
Source File: MissionPane.java    From logbook-kai with MIT License 5 votes vote down vote up
@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);
    }
}
 
Example #23
Source File: AdditionalServiceRepository.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@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);
 
Example #24
Source File: TCKZonedDateTime.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #25
Source File: TCKZonedDateTime.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@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
}
 
Example #26
Source File: TestDateTimeFormatter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@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, "");
}
 
Example #27
Source File: TCKOffsetPrinterParser.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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));
    }
}
 
Example #28
Source File: TCKOffsetPrinterParser.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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);
    }
}
 
Example #29
Source File: ZonedDateTimeCodec.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #30
Source File: TCKZonedDateTime.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@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
}