java.time.ZoneId Java Examples

The following examples show how to use java.time.ZoneId. 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: TestZoneId.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void test_NewYork_getOffsetInfo_gap() {
    ZoneId test = ZoneId.of("America/New_York");
    final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 9, 2, 0, 0, 0);
    ZoneOffsetTransition trans = checkOffset(test.getRules(), dateTime, ZoneOffset.ofHours(-5), GAP);
    assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-5));
    assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-4));
    assertEquals(trans.getInstant(), createInstant(2008, 3, 9, 2, 0, 0, 0, ZoneOffset.ofHours(-5)));
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-6)), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-3)), false);
    assertEquals(trans.toString(), "Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]");

    assertFalse(trans.equals(null));
    assertFalse(trans.equals(ZoneOffset.ofHours(-5)));
    assertTrue(trans.equals(trans));

    final ZoneOffsetTransition otherTrans = test.getRules().getTransition(dateTime);
    assertTrue(trans.equals(otherTrans));

    assertEquals(trans.hashCode(), otherTrans.hashCode());
}
 
Example #2
Source File: DefaultSystemStatusUtilityTest.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void startupOccurred() {
    SystemStatusRepository systemStatusRepository = new MockSystemStatusRepository(Boolean.FALSE);
    DefaultSystemStatusUtility systemStatusUtility = new DefaultSystemStatusUtility(systemStatusRepository);
    systemStatusUtility.startupOccurred();

    //createCurrentDateTimestamp can't be modified, so the expected values for getStartupTime must be estimated
    LocalDateTime estimatedDate = LocalDateTime.now();
    SystemStatusEntity testSystemStatus = systemStatusRepository.findAll().get(0);
    LocalDateTime systemStatusLocalDateTime = testSystemStatus.getStartupTime()
                                                  .toInstant()
                                                  .atZone(ZoneId.systemDefault())
                                                  .toLocalDateTime();

    assertFalse(testSystemStatus.isInitialConfigurationPerformed());
    assertNotNull(testSystemStatus.getStartupTime());
    assertEquals(estimatedDate.getHour(), systemStatusLocalDateTime.getHour());
    assertEquals(estimatedDate.getMinute(), systemStatusLocalDateTime.getMinute());
}
 
Example #3
Source File: Bug8024141.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    ZoneId gmt = ZoneId.of("GMT");
    String gmtName = gmt.getDisplayName(FULL, ENGLISH);
    String gmtAbbr = gmt.getDisplayName(SHORT, ENGLISH);

    for (String zone : ZONES) {
        ZoneId id = ZoneId.of(zone);
        String name = id.getDisplayName(FULL, ENGLISH);
        String abbr = id.getDisplayName(SHORT, ENGLISH);

        if (!name.equals(gmtName) || !abbr.equals(gmtAbbr)) {
            throw new RuntimeException("inconsistent name/abbr for " + zone + ":\n"
                                       + "name=" + name + ", abbr=" + abbr);
        }
    }
}
 
Example #4
Source File: TCKZoneIdPrinterParser.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="parseSuccess")
public void test_parseSuccess_prefix(String text, int expectedIndex, int expectedErrorIndex, ZoneId expected) {
    builder.appendZoneId();
    pos.setIndex(3);
    String prefixText = "XXX" + text;
    TemporalAccessor parsed = builder.toFormatter().parseUnresolved(prefixText, pos);
    assertEquals(pos.getErrorIndex(), expectedErrorIndex >= 0  ? expectedErrorIndex + 3 : expectedErrorIndex, "Incorrect error index parsing: " + prefixText);
    assertEquals(pos.getIndex(), expectedIndex + 3, "Incorrect index parsing: " + prefixText);
    if (expected != null) {
        assertEquals(parsed.query(TemporalQueries.zoneId()), expected, "Incorrect zoneId parsing: " + prefixText);
        assertEquals(parsed.query(TemporalQueries.offset()), null, "Incorrect offset parsing: " + prefixText);
        assertEquals(parsed.query(TemporalQueries.zone()), expected, "Incorrect zone parsing: " + prefixText);
    } else {
        assertEquals(parsed, null);
    }
}
 
Example #5
Source File: JavaTimeConverterServiceTest.java    From SimpleFlatMapper with MIT License 6 votes vote down vote up
@Test
public void testObjectToOffsetDateTime() throws Exception {
    ZoneId zoneId = ZONE_ID;
    OffsetDateTime offsetDateTime = OffsetDateTime.now(zoneId);

    testObjectToOffsetDateTime(null, null);
    testObjectToOffsetDateTime(offsetDateTime, offsetDateTime);

    testObjectToOffsetDateTime(offsetDateTime.toLocalDateTime(), offsetDateTime);
    testObjectToOffsetDateTime(offsetDateTime.toInstant(), offsetDateTime);
    testObjectToOffsetDateTime(offsetDateTime.atZoneSameInstant(zoneId), offsetDateTime);
    testObjectToOffsetDateTime(offsetDateTime.atZoneSameInstant(zoneId), offsetDateTime);
    testObjectToOffsetDateTime(offsetDateTime.toLocalDate(), offsetDateTime.truncatedTo(ChronoUnit.DAYS));

    testObjectToOffsetDateTime(Date.from(offsetDateTime.toInstant()), offsetDateTime.truncatedTo(ChronoUnit.MILLIS));

    try {
        testObjectToOffsetDateTime("a string", offsetDateTime);
        fail();
    } catch (IllegalArgumentException e) {
        // expected
    }
}
 
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_jumpOverInternationalDateLine_M10_to_P14() {
    // transition occurred at 2011-12-30T00:00-10:00
    ZoneRules test = pacificApia();
    Instant instantBefore = LocalDate.of(2011, 12, 27).atStartOfDay(ZoneOffset.UTC).toInstant();
    ZoneOffsetTransition trans = test.nextTransition(instantBefore);
    assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2011, 12, 30, 0, 0));
    assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2011, 12, 31, 0, 0));
    assertEquals(trans.isGap(), true);
    assertEquals(trans.isOverlap(), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-10)), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(+14)), false);
    assertEquals(trans.getDuration(), Duration.ofHours(24));
    assertEquals(trans.getInstant(), LocalDateTime.of(2011, 12, 31, 0, 0).toInstant(ZoneOffset.ofHours(+14)));

    ZonedDateTime zdt = ZonedDateTime.of(2011, 12, 29, 23, 0, 0, 0, ZoneId.of("Pacific/Apia"));
    assertEquals(zdt.plusHours(2).toLocalDateTime(), LocalDateTime.of(2011, 12, 31, 1, 0));
}
 
Example #7
Source File: I18nConfigOptionsProvider.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
private @Nullable Collection<ParameterOption> processParamType(String param, @Nullable Locale locale,
        Locale translation) {
    switch (param) {
        case "language":
            return getAvailable(locale,
                    l -> new ParameterOption(l.getLanguage(), l.getDisplayLanguage(translation)));
        case "region":
            return getAvailable(locale, l -> new ParameterOption(l.getCountry(), l.getDisplayCountry(translation)));
        case "variant":
            return getAvailable(locale, l -> new ParameterOption(l.getVariant(), l.getDisplayVariant(translation)));
        case "timezone":
            Comparator<TimeZone> byOffset = (t1, t2) -> {
                return t1.getRawOffset() - t2.getRawOffset();
            };
            Comparator<TimeZone> byID = (t1, t2) -> {
                return t1.getID().compareTo(t2.getID());
            };
            return ZoneId.getAvailableZoneIds().stream().map(TimeZone::getTimeZone)
                    .sorted(byOffset.thenComparing(byID)).map(tz -> {
                        return new ParameterOption(tz.getID(), getTimeZoneRepresentation(tz));
                    }).collect(Collectors.toList());
        default:
            return null;
    }
}
 
Example #8
Source File: MockNodeRepository.java    From vespa with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor
 *
 * @param flavors flavors to have in node repo
 */
public MockNodeRepository(MockCurator curator, NodeFlavors flavors) {
    super(flavors,
          new EmptyProvisionServiceProvider().getHostResourcesCalculator(),
          curator,
          Clock.fixed(Instant.ofEpochMilli(123), ZoneId.of("Z")),
          Zone.defaultZone(),
          new MockNameResolver().mockAnyLookup(),
          DockerImage.fromString("docker-registry.domain.tld:8080/dist/vespa"),
          true,
          false,
          0);
    this.flavors = flavors;

    curator.setZooKeeperEnsembleConnectionSpec("cfg1:1234,cfg2:1234,cfg3:1234");
    populate();
}
 
Example #9
Source File: TestZoneId.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void test_NewYork_getOffsetInfo_gap() {
    ZoneId test = ZoneId.of("America/New_York");
    final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 9, 2, 0, 0, 0);
    ZoneOffsetTransition trans = checkOffset(test.getRules(), dateTime, ZoneOffset.ofHours(-5), GAP);
    assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-5));
    assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-4));
    assertEquals(trans.getInstant(), createInstant(2008, 3, 9, 2, 0, 0, 0, ZoneOffset.ofHours(-5)));
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-6)), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-3)), false);
    assertEquals(trans.toString(), "Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]");

    assertFalse(trans.equals(null));
    assertFalse(trans.equals(ZoneOffset.ofHours(-5)));
    assertTrue(trans.equals(trans));

    final ZoneOffsetTransition otherTrans = test.getRules().getTransition(dateTime);
    assertTrue(trans.equals(otherTrans));

    assertEquals(trans.hashCode(), otherTrans.hashCode());
}
 
Example #10
Source File: IndexNameHelperTest.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void dateInCurrentWeek() throws Exception
{
    LocalDateTime expectedSpanStart = LocalDateTime.of(2018, 9, 9, 0, 0, 0);
    LocalDateTime expectedSpanEnd = LocalDateTime.of(2018, 9, 16, 0, 0, 0);
    LocalDateTime oldSpanTime = LocalDateTime.of(2018, 9, 13, 0, 0, 0);
    LocalDateTime newSpanTime = LocalDateTime.of(2018, 9, 14, 0, 0, 0);

    IndexNameHelper inh = new IndexNameHelper("test_index", "w", 1);

    assertNull(inh.getCurrentDateSpanStart());
    assertNull(inh.getCurrentDateSpanEnd());

    assertEquals("test_index_2018-09-09", inh.getIndexName(oldSpanTime.atZone(ZoneId.systemDefault()).toInstant()));
    assertEquals(expectedSpanStart.atZone(ZoneId.systemDefault()).toInstant(), inh.getCurrentDateSpanStart());
    assertEquals(expectedSpanEnd.atZone(ZoneId.systemDefault()).toInstant(), inh.getCurrentDateSpanEnd());

    assertEquals("test_index_2018-09-09", inh.getIndexName(newSpanTime.atZone(ZoneId.systemDefault()).toInstant()));
    assertEquals(expectedSpanStart.atZone(ZoneId.systemDefault()).toInstant(), inh.getCurrentDateSpanStart());
    assertEquals(expectedSpanEnd.atZone(ZoneId.systemDefault()).toInstant(), inh.getCurrentDateSpanEnd());
}
 
Example #11
Source File: AckSenderService.java    From springboot-learn with MIT License 6 votes vote down vote up
/**
 * 消息发送
 */
public void send() {
    final String content = "现在时间是" + LocalDateTime.now(ZoneId.systemDefault());

    //设置返回回调
    rabbitTemplate.setReturnCallback(this);
    //设置确认回调
    rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
        if (ack) {
            System.out.println("消息发送成功!");
        } else {
            System.out.println("消息发送失败," + cause + correlationData.toString());
        }
    });
    rabbitTemplate.convertAndSend("ackQueue", content);
}
 
Example #12
Source File: TCKZoneId.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void test_equals() {
    ZoneId test1 = ZoneId.of("Europe/London");
    ZoneId test2 = ZoneId.of("Europe/Paris");
    ZoneId test2b = ZoneId.of("Europe/Paris");
    assertEquals(test1.equals(test2), false);
    assertEquals(test2.equals(test1), false);

    assertEquals(test1.equals(test1), true);
    assertEquals(test2.equals(test2), true);
    assertEquals(test2.equals(test2b), true);

    assertEquals(test1.hashCode() == test1.hashCode(), true);
    assertEquals(test2.hashCode() == test2.hashCode(), true);
    assertEquals(test2.hashCode() == test2b.hashCode(), true);
}
 
Example #13
Source File: TCKLocalDate.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void now_ZoneId() {
    ZoneId zone = ZoneId.of("UTC+01:02:03");
    LocalDate expected = LocalDate.now(Clock.system(zone));
    LocalDate test = LocalDate.now(zone);
    for (int i = 0; i < 100; i++) {
        if (expected.equals(test)) {
            return;
        }
        expected = LocalDate.now(Clock.system(zone));
        test = LocalDate.now(zone);
    }
    assertEquals(test, expected);
}
 
Example #14
Source File: JinjavaConfig.java    From jinjava with Apache License 2.0 5 votes vote down vote up
private JinjavaConfig(
  Charset charset,
  Locale locale,
  ZoneId timeZone,
  int maxRenderDepth,
  Map<Context.Library, Set<String>> disabled,
  boolean trimBlocks,
  boolean lstripBlocks,
  boolean enableRecursiveMacroCalls,
  int maxMacroRecursionDepth,
  boolean failOnUnknownTokens,
  long maxOutputSize,
  boolean nestedInterpretationEnabled,
  RandomNumberGeneratorStrategy randomNumberGenerator,
  boolean validationMode,
  long maxStringLength,
  InterpreterFactory interpreterFactory,
  TokenScannerSymbols tokenScannerSymbols,
  ELResolver elResolver
) {
  this.charset = charset;
  this.locale = locale;
  this.timeZone = timeZone;
  this.maxRenderDepth = maxRenderDepth;
  this.disabled = disabled;
  this.trimBlocks = trimBlocks;
  this.lstripBlocks = lstripBlocks;
  this.enableRecursiveMacroCalls = enableRecursiveMacroCalls;
  this.maxMacroRecursionDepth = maxMacroRecursionDepth;
  this.failOnUnknownTokens = failOnUnknownTokens;
  this.maxOutputSize = maxOutputSize;
  this.nestedInterpretationEnabled = nestedInterpretationEnabled;
  this.randomNumberGenerator = randomNumberGenerator;
  this.validationMode = validationMode;
  this.maxStringLength = maxStringLength;
  this.interpreterFactory = interpreterFactory;
  this.tokenScannerSymbols = tokenScannerSymbols;
  this.elResolver = elResolver;
}
 
Example #15
Source File: TestZoneId.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void test_constant_UTC() {
    ZoneId test = ZoneOffset.UTC;
    assertEquals(test.getId(), "Z");
    assertEquals(test.getDisplayName(TextStyle.FULL, Locale.UK), "Z");
    assertEquals(test.getRules().isFixedOffset(), true);
    assertEquals(test.getRules().getOffset(Instant.ofEpochSecond(0L)), ZoneOffset.UTC);
    checkOffset(test.getRules(), createLDT(2008, 6, 30), ZoneOffset.UTC, 1);
}
 
Example #16
Source File: MinutesIntervalSchedulerFactory.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Override
public Scheduler newScheduler(Config config, ZoneId timeZone)
{
    int interval = config.get("_command", int.class);
    long delay = config.get("delay", long.class, 0L);
    return new CronScheduler("*/" + interval + " * * * *", timeZone, delay);
}
 
Example #17
Source File: TestZoneId.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void test_NewYork_getOffsetInfo() {
    ZoneId test = ZoneId.of("America/New_York");
    checkOffset(test.getRules(), createLDT(2008, 1, 1), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 2, 1), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 3, 1), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 4, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 5, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 6, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 7, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 8, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 9, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 12, 1), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 1, 28), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 2, 28), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 3, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 4, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 5, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 6, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 7, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 8, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 9, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 28), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 12, 28), ZoneOffset.ofHours(-5), 1);
}
 
Example #18
Source File: TCKZoneId.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_of_string_Map_lookThrough() {
    Map<String, String> map = new HashMap<>();
    map.put("LONDON", "Europe/London");
    map.put("PARIS", "Europe/Paris");
    ZoneId test = ZoneId.of("Europe/Madrid", map);
    assertEquals(test.getId(), "Europe/Madrid");
}
 
Example #19
Source File: JavaDateFormatter.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public DateFormatter withZone(ZoneId zoneId) {
    // shortcurt to not create new objects unnecessarily
    if (zoneId.equals(parsers[0].getZone())) {
        return this;
    }

    final DateTimeFormatter[] parsersWithZone = new DateTimeFormatter[parsers.length];
    for (int i = 0; i < parsers.length; i++) {
        parsersWithZone[i] = parsers[i].withZone(zoneId);
    }

    return new JavaDateFormatter(format, printer.withZone(zoneId), parsersWithZone);
}
 
Example #20
Source File: TCKChronology.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_IsoChronology_dateNow() {
    ZoneId zoneId_paris = ZoneId.of("Europe/Paris");
    Clock clock = Clock.system(zoneId_paris);

    Chronology chrono = Chronology.of("ISO");
    assertEquals(chrono.dateNow(), IsoChronology.INSTANCE.dateNow());
    assertEquals(chrono.dateNow(zoneId_paris), IsoChronology.INSTANCE.dateNow(zoneId_paris));
    assertEquals(chrono.dateNow(clock), IsoChronology.INSTANCE.dateNow(clock));
}
 
Example #21
Source File: TestZoneId.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void test_NewYork_getOffsetInfo_fromDST() {
    ZoneId test = ZoneId.of("America/New_York");
    checkOffset(test.getRules(), createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 2), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 3), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 4), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 5), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 6), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 7), ZoneOffset.ofHours(-5), 1);
    // cutover at 02:00 local
    checkOffset(test.getRules(), LocalDateTime.of(2008, 11, 2, 0, 59, 59, 999999999), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), LocalDateTime.of(2008, 11, 2, 1, 30, 0, 0), ZoneOffset.ofHours(-4), OVERLAP);
    checkOffset(test.getRules(), LocalDateTime.of(2008, 11, 2, 2, 0, 0, 0), ZoneOffset.ofHours(-5), 1);
}
 
Example #22
Source File: TCKZoneId.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="offsetBasedValid")
public void factory_of_String_offsetBasedValid_noPrefix(String input, String id) {
    ZoneId test = ZoneId.of(input);
    assertEquals(test.getId(), id);
    assertEquals(test, ZoneOffset.of(id));
    assertEquals(test.normalized(), ZoneOffset.of(id));
    assertEquals(test.getDisplayName(TextStyle.FULL, Locale.UK), id);
    assertEquals(test.getRules().isFixedOffset(), true);
    assertEquals(test.getRules().getOffset(Instant.EPOCH), ZoneOffset.of(id));
}
 
Example #23
Source File: TCKZoneId.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="prefixValid")
public void test_prefixOfOffset(String prefix, String offset) {
    ZoneOffset zoff = ZoneOffset.of(offset);
    ZoneId zoneId = ZoneId.ofOffset(prefix, zoff);
    assertEquals(zoneId.getId(), prefix + zoff.getId(), "in correct id for : " + prefix + ", zoff: " + zoff);

}
 
Example #24
Source File: TestZoneId.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void test_immutable() {
    // cannot use standard test as ZoneId is abstract
    Class<ZoneId> cls = ZoneId.class;
    assertTrue(Modifier.isPublic(cls.getModifiers()));
    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
        if (Modifier.isStatic(field.getModifiers()) == false) {
            assertTrue(Modifier.isPrivate(field.getModifiers()));
            assertTrue(Modifier.isFinal(field.getModifiers()) ||
                    (Modifier.isVolatile(field.getModifiers()) && Modifier.isTransient(field.getModifiers())));
        }
    }
}
 
Example #25
Source File: TCKZoneId.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="offsetBasedInvalid", expectedExceptions=DateTimeException.class)
public void factory_of_String_offsetBasedInvalid_prefixGMT(String id) {
    if (id.equals("0")) {
        throw new DateTimeException("Fake exception: GMT0 is valid, not invalid");
    }
    ZoneId.of("GMT" + id);
}
 
Example #26
Source File: LocalDatePersistenceConverter.java    From aprendendo-vraptor with Apache License 2.0 5 votes vote down vote up
@Override
public Date convertToDatabaseColumn(LocalDate localDate) {
	
	if(localDate != null) {
		Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
		return Date.from(instant);
	}
	
	return null;
}
 
Example #27
Source File: StripeManagerTest.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    transactionRepository = mock(TransactionRepository.class);
    configurationManager = mock(ConfigurationManager.class);
    ticketRepository = mock(TicketRepository.class);
    event = mock(Event.class);
    when(event.getZoneId()).thenReturn(ZoneId.systemDefault());
    customerName = mock(CustomerName.class);
    configurationRepository = mock(ConfigurationRepository.class);
    when(customerName.getFullName()).thenReturn("ciccio");
    when(configurationManager.getFor(eq(PLATFORM_MODE_ENABLED), any())).thenReturn(new ConfigurationManager.MaybeConfiguration(PLATFORM_MODE_ENABLED));
}
 
Example #28
Source File: EdmTimeOfDay.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected <T> T internalValueOfString(final String value, final Boolean isNullable, final Integer maxLength,
    final Integer precision, final Integer scale, final Boolean isUnicode, final Class<T> returnType)
    throws EdmPrimitiveTypeException {
  LocalTime time;
  try {
    time = LocalTime.parse(value);
  } catch (DateTimeParseException ex) {
    throw new EdmPrimitiveTypeException("The literal '" + value + "' has illegal content.");
  }

  // appropriate types
  if (returnType.isAssignableFrom(LocalTime.class)) {
    return (T) time;
  } else if (returnType.isAssignableFrom(java.sql.Time.class)) {
    return (T) java.sql.Time.valueOf(time);
  }

  // inappropriate types, which need to be supported for backward compatibility
  ZonedDateTime zdt = LocalDateTime.of(EPOCH, time).atZone(ZoneId.systemDefault());
  if (returnType.isAssignableFrom(Calendar.class)) {
    return (T) GregorianCalendar.from(zdt);
  } else if (returnType.isAssignableFrom(Long.class)) {
    return (T) Long.valueOf(zdt.toInstant().toEpochMilli());
  } else if (returnType.isAssignableFrom(java.sql.Date.class)) {
    throw new EdmPrimitiveTypeException("The value type " + returnType + " is not supported.");
  } else if (returnType.isAssignableFrom(Timestamp.class)) {
    return (T) Timestamp.from(zdt.toInstant());
  } else if (returnType.isAssignableFrom(java.util.Date.class)) {
    return (T) java.util.Date.from(zdt.toInstant());
  } else {
    throw new EdmPrimitiveTypeException("The value type " + returnType + " is not supported.");
  }
}
 
Example #29
Source File: TestZonedDateTimeSerialization.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializationAsInt03NanosecondsWithTimeZone() throws Exception
{
    ZonedDateTime date = ZonedDateTime.now(Z3);
    date = date.minus(date.getNano(), ChronoUnit.NANOS);
    ObjectMapper mapper = newMapper(TimeZone.getDefault());
    ZonedDateTime value = mapper.readerFor(ZonedDateTime.class)
            .with(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)
            .readValue(Long.toString(date.toEpochSecond()));
    assertIsEqual(date, value);
    assertEquals("The time zone is not correct.", ZoneId.systemDefault(), value.getZone());
}
 
Example #30
Source File: WriteBehindCacheWriterTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Test
public void givenMultipleCacheUpdatesOnSameKey_writeBehindIsCalledWithMostRecentTime() {
  AtomicBoolean writerCalled = new AtomicBoolean(false);
  AtomicInteger numberOfEntries = new AtomicInteger(0);
  AtomicReference<ZonedDateTime> timeInWriteBehind = new AtomicReference<>();

  // Given this cache...
  Cache<Long, ZonedDateTime> cache = Caffeine.newBuilder()
      .writer(new WriteBehindCacheWriter.Builder<Long, ZonedDateTime>()
          .bufferTime(1, TimeUnit.SECONDS)
          .coalesce(BinaryOperator.maxBy(ZonedDateTime::compareTo))
          .writeAction(entries -> {
            // We might get here before the cache has been written to,
            // so just wait for the next time we are called
            if (entries.isEmpty()) {
              return;
            }

            numberOfEntries.set(entries.size());
            ZonedDateTime zonedDateTime = entries.values().iterator().next();
            timeInWriteBehind.set(zonedDateTime);
            writerCalled.set(true);
          }).build())
      .build();

  // When these cache updates happen ...
  cache.put(1L, ZonedDateTime.of(2016, 6, 26, 8, 0, 0, 0, ZoneId.systemDefault()));
  cache.put(1L, ZonedDateTime.of(2016, 6, 26, 8, 0, 0, 100, ZoneId.systemDefault()));
  cache.put(1L, ZonedDateTime.of(2016, 6, 26, 8, 0, 0, 300, ZoneId.systemDefault()));
  ZonedDateTime mostRecentTime = ZonedDateTime.of(
      2016, 6, 26, 8, 0, 0, 500, ZoneId.systemDefault());
  cache.put(1L, mostRecentTime);

  // Then the write behind action gets 1 entry to write with the most recent time
  Awaitility.await().untilTrue(writerCalled);
  Assert.assertEquals(1, numberOfEntries.intValue());
  Assert.assertEquals(mostRecentTime, timeInWriteBehind.get());
}