下面列出了怎么用java.time.ZoneOffset的API类实例代码及写法,或者点击链接到github查看源代码。
@Test(dataProvider = "signStyle")
public void test_signStyle(LocalDate localDate, SignStyle style, Class<?> expectedEx, String expectedStr) {
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
DateTimeFormatter formatter = builder.appendValue(ChronoField.YEAR, 2, 4, style)
.toFormatter();
formatter = formatter.withZone(ZoneOffset.UTC);
if (expectedEx == null) {
String output = formatter.format(localDate);
assertEquals(output, expectedStr);
} else {
try {
formatter.format(localDate);
fail();
} catch (Exception ex) {
assertTrue(expectedEx.isInstance(ex));
}
}
}
@Test
void createDashboard() {
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
Dashboard dashboard = dashboardsApi.createDashboard(generateName("dashboard"), "coolest dashboard", organization.getId());
Assertions.assertThat(dashboard).isNotNull();
Assertions.assertThat(dashboard.getId()).isNotEmpty();
Assertions.assertThat(dashboard.getOrgID()).isEqualTo(organization.getId());
Assertions.assertThat(dashboard.getCells()).hasSize(0);
Assertions.assertThat(dashboard.getMeta()).isNotNull();
Assertions.assertThat(dashboard.getMeta().getCreatedAt()).isAfter(now);
Assertions.assertThat(dashboard.getMeta().getUpdatedAt()).isAfter(now);
Assertions.assertThat(dashboard.getLabels()).hasSize(0);
Assertions.assertThat(dashboard.getLinks()).isNotNull();
Assertions.assertThat(dashboard.getLinks().getSelf()).isEqualTo("/api/v2/dashboards/" + dashboard.getId());
Assertions.assertThat(dashboard.getLinks().getMembers()).isEqualTo("/api/v2/dashboards/" + dashboard.getId() + "/members");
Assertions.assertThat(dashboard.getLinks().getOwners()).isEqualTo("/api/v2/dashboards/" + dashboard.getId() + "/owners");
Assertions.assertThat(dashboard.getLinks().getCells()).isEqualTo("/api/v2/dashboards/" + dashboard.getId() + "/cells");
Assertions.assertThat(dashboard.getLinks().getLabels()).isEqualTo("/api/v2/dashboards/" + dashboard.getId() + "/labels");
Assertions.assertThat(dashboard.getLinks().getOrg()).isEqualTo("/api/v2/orgs/" + organization.getId());
}
@Override
public void afterInit() {
doInJPA(entityManager -> {
Post post = new Post();
post.setId(1L);
post.setTitle("High-Performance Java Persistence");
post.setCreatedBy("Vlad Mihalcea");
post.setCreatedOn(Timestamp.from(
LocalDateTime.of(2020, 11, 2, 12, 0, 0).toInstant(ZoneOffset.UTC)
));
post.setUpdatedBy("Vlad Mihalcea");
post.setUpdatedOn(Timestamp.from(
LocalDateTime.now().toInstant(ZoneOffset.UTC)
));
entityManager.persist(post);
});
}
@Test
void simpleEncodeAndDecodeTest() throws Exception {
long now = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS)
.toInstant(ZoneOffset.UTC).toEpochMilli();
Pair[] pairs = {
new Pair(now + 10, Double.doubleToRawLongBits(1.0)),
new Pair(now + 20, Double.doubleToRawLongBits(-2.0)),
new Pair(now + 28, Double.doubleToRawLongBits(-2.5)),
new Pair(now + 84, Double.doubleToRawLongBits(65537)),
new Pair(now + 400, Double.doubleToRawLongBits(2147483650.0)),
new Pair(now + 2300, Double.doubleToRawLongBits(-16384)),
new Pair(now + 16384, Double.doubleToRawLongBits(2.8)),
new Pair(now + 16500, Double.doubleToRawLongBits(-38.0))
};
comparePairsToCompression(now, pairs);
}
public void test_Apia_jumpForwardOverInternationalDateLine_P12_to_M12() {
// transition occurred at 1892-07-04T00:00+12:33:04
ZoneRules test = pacificApia();
Instant instantBefore = LocalDate.of(1892, 7, 2).atStartOfDay(ZoneOffset.UTC).toInstant();
ZoneOffsetTransition trans = test.nextTransition(instantBefore);
assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(1892, 7, 5, 0, 0));
assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(1892, 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(1892, 7, 4, 0, 0).toInstant(ZoneOffset.ofHoursMinutesSeconds(-11, -26, -56)));
ZonedDateTime zdt = ZonedDateTime.of(1892, 7, 4, 23, 0, 0, 0, ZoneId.of("Pacific/Apia"));
assertEquals(zdt.plusHours(2).toLocalDateTime(), LocalDateTime.of(1892, 7, 4, 1, 0, 0));
}
@Test(dataProvider="sampleTimes")
public void test_get(int y, int o, int d, int h, int m, int s, int n, ZoneOffset offset) {
LocalDate localDate = LocalDate.of(y, o, d);
LocalTime localTime = LocalTime.of(h, m, s, n);
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
OffsetDateTime a = OffsetDateTime.of(localDateTime, offset);
assertEquals(a.getYear(), localDate.getYear());
assertEquals(a.getMonth(), localDate.getMonth());
assertEquals(a.getDayOfMonth(), localDate.getDayOfMonth());
assertEquals(a.getDayOfYear(), localDate.getDayOfYear());
assertEquals(a.getDayOfWeek(), localDate.getDayOfWeek());
assertEquals(a.getHour(), localDateTime.getHour());
assertEquals(a.getMinute(), localDateTime.getMinute());
assertEquals(a.getSecond(), localDateTime.getSecond());
assertEquals(a.getNano(), localDateTime.getNano());
assertEquals(a.toOffsetTime(), OffsetTime.of(localTime, offset));
assertEquals(a.toString(), localDateTime.toString() + offset.toString());
}
/**
* Reads the state from the stream.
*
* @param in the input stream, not null
* @return the created object, not null
* @throws IOException if an error occurs
*/
static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException {
int data = in.readInt();
Month month = Month.of(data >>> 28);
int dom = ((data & (63 << 22)) >>> 22) - 32;
int dowByte = (data & (7 << 19)) >>> 19;
DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte);
int timeByte = (data & (31 << 14)) >>> 14;
TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12];
int stdByte = (data & (255 << 4)) >>> 4;
int beforeByte = (data & (3 << 2)) >>> 2;
int afterByte = (data & 3);
LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0));
ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900));
ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800));
ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800));
return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after);
}
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());
}
public void test_London_getOffsetInfo_gap() {
ZoneRules test = europeLondon();
final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 1, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_ZERO, GAP);
assertEquals(trans.isGap(), true);
assertEquals(trans.isOverlap(), false);
assertEquals(trans.getOffsetBefore(), OFFSET_ZERO);
assertEquals(trans.getOffsetAfter(), OFFSET_PONE);
assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC));
assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 3, 30, 1, 0));
assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 3, 30, 2, 0));
assertEquals(trans.isValidOffset(OFFSET_ZERO), false);
assertEquals(trans.isValidOffset(OFFSET_PONE), false);
assertEquals(trans.isValidOffset(OFFSET_PTWO), false);
assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T01:00Z to +01:00]");
assertFalse(trans.equals(null));
assertFalse(trans.equals(OFFSET_ZERO));
assertTrue(trans.equals(trans));
final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
assertTrue(trans.equals(otherTrans));
assertEquals(trans.hashCode(), otherTrans.hashCode());
}
@Override
void setupData(Transaction transaction) {
ZonedDateTime createdAt = LocalDateTime.of(2019, 1, 1, 23, 23, 42, 0).atZone(ZoneOffset.UTC.normalized());
id1 = transaction.run("" +
"CREATE (n:PersonWithAllConstructor) " +
" SET n.name = $name, n.sameValue = $sameValue, n.first_name = $firstName, n.cool = $cool, n.personNumber = $personNumber, n.bornOn = $bornOn, n.nullable = 'something', n.things = ['a', 'b'], n.place = $place, n.createdAt = $createdAt "
+
"RETURN id(n)",
Values.parameters("name", TEST_PERSON1_NAME, "sameValue", TEST_PERSON_SAMEVALUE, "firstName",
TEST_PERSON1_FIRST_NAME, "cool", true, "personNumber", 1, "bornOn", TEST_PERSON1_BORN_ON, "place",
NEO4J_HQ, "createdAt", createdAt)
).next().get(0).asLong();
transaction
.run("CREATE (a:Thing {theId: 'anId', name: 'Homer'})-[:Has]->(b:Thing2{theId: 4711, name: 'Bart'})");
IntStream.rangeClosed(1, 20).forEach(i ->
transaction.run("CREATE (a:Thing {theId: 'id' + $i, name: 'name' + $i})",
Values.parameters("i", String.format("%02d", i))));
person1 = new PersonWithAllConstructor(id1, TEST_PERSON1_NAME, TEST_PERSON1_FIRST_NAME,
TEST_PERSON_SAMEVALUE,
true, 1L, TEST_PERSON1_BORN_ON, "something", Arrays.asList("a", "b"), NEO4J_HQ, createdAt.toInstant());
}
@Test
public void test_dateNow(){
assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now()) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now(ZoneId.systemDefault())) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now(Clock.systemDefaultZone())) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now(Clock.systemDefaultZone().getZone())) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoChronology.INSTANCE.dateNow(ZoneId.systemDefault())) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoChronology.INSTANCE.dateNow(Clock.systemDefaultZone())) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone())) ;
ZoneId zoneId = ZoneId.of("Europe/Paris");
assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoChronology.INSTANCE.dateNow(Clock.system(zoneId))) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone())) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoDate.now(Clock.system(zoneId))) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoDate.now(Clock.system(zoneId).getZone())) ;
assertEquals(MinguoChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId())), MinguoChronology.INSTANCE.dateNow(Clock.systemUTC())) ;
}
public void test_London_getStandardOffset() {
ZoneRules test = europeLondon();
ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC);
while (zdt.getYear() < 2010) {
Instant instant = zdt.toInstant();
if (zdt.getYear() < 1848) {
assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15));
} else if (zdt.getYear() >= 1969 && zdt.getYear() < 1972) {
assertEquals(test.getStandardOffset(instant), OFFSET_PONE);
} else {
assertEquals(test.getStandardOffset(instant), OFFSET_ZERO);
}
zdt = zdt.plusMonths(6);
}
}
@Test(dataProvider="sampleTimes")
public void test_equals_false_second_differs(int y, int o, int d, int h, int m, int s, int n, ZoneOffset ignored) {
s = (s == 59 ? 58 : s);
OffsetDateTime a = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE);
OffsetDateTime b = OffsetDateTime.of(y, o, d, h, m, s + 1, n, OFFSET_PONE);
assertEquals(a.equals(b), false);
}
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofInstant_tooLow() {
long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7);
int year = Year.MIN_VALUE - 1;
long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970;
Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L);
OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
}
/**
* Gets the offset applicable at the specified instant in these rules.
* <p>
* The mapping from an instant to an offset is simple, there is only
* one valid offset for each instant.
* This method returns that offset.
*
* @param instant the instant to find the offset for, not null, but null
* may be ignored if the rules have a single offset for all instants
* @return the offset, not null
*/
public ZoneOffset getOffset(Instant instant) {
if (savingsInstantTransitions.length == 0) {
return standardOffsets[0];
}
long epochSec = instant.getEpochSecond();
// check if using last rules
if (lastRules.length > 0 &&
epochSec > savingsInstantTransitions[savingsInstantTransitions.length - 1]) {
int year = findYear(epochSec, wallOffsets[wallOffsets.length - 1]);
ZoneOffsetTransition[] transArray = findTransitionArray(year);
ZoneOffsetTransition trans = null;
for (int i = 0; i < transArray.length; i++) {
trans = transArray[i];
if (epochSec < trans.toEpochSecond()) {
return trans.getOffsetBefore();
}
}
return trans.getOffsetAfter();
}
// using historic rules
int index = Arrays.binarySearch(savingsInstantTransitions, epochSec);
if (index < 0) {
// switch negative insert position to start of matched range
index = -index - 2;
}
return wallOffsets[index + 1];
}
@Test
public void insufficientTimeHasPassedSinceTheLastRun() {
underTest = new LanderMonitor(Clock.fixed(THREE_MINUTES_PAST_EPOCH, ZoneOffset.UTC), runnable,
OffsetDateTime.ofInstant(FIVE_MINUTES_PAST_EPOCH, ZoneOffset.UTC), executorService, random, true);
underTest.establishLandingFrequency(PT1M);
when(runnable.isRunning()).thenReturn(false);
underTest.setEnabled(true);
underTest.execute();
verify(runnable, never()).run(any());
}
@Test(dataProvider="sampleTimes")
public void test_equals_false_hour_differs(int y, int o, int d, int h, int m, int s, int n, ZoneOffset ignored) {
h = (h == 23 ? 22 : h);
OffsetDateTime a = OffsetDateTime.of(y, o, d, h, m, s, n, OFFSET_PONE);
OffsetDateTime b = OffsetDateTime.of(y, o, d, h + 1, m, s, n, OFFSET_PONE);
assertEquals(a.equals(b), false);
}
@Test
public void test_factory_int_hours_minutes() {
for (int i = -17; i <= 17; i++) {
for (int j = -59; j <= 59; j++) {
if ((i < 0 && j <= 0) || (i > 0 && j >= 0) || i == 0) {
ZoneOffset test = ZoneOffset.ofHoursMinutes(i, j);
doTestOffset(test, i, j, 0);
}
}
}
ZoneOffset test1 = ZoneOffset.ofHoursMinutes(-18, 0);
doTestOffset(test1, -18, 0, 0);
ZoneOffset test2 = ZoneOffset.ofHoursMinutes(18, 0);
doTestOffset(test2, 18, 0, 0);
}
public void test_Paris_preTimeZones() {
ZoneRules test = europeParis();
ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC);
Instant instant = old.toInstant();
ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, 9, 21);
assertEquals(test.getOffset(instant), offset);
checkOffset(test, old.toLocalDateTime(), offset, 1);
assertEquals(test.getStandardOffset(instant), offset);
assertEquals(test.getDaylightSavings(instant), Duration.ZERO);
assertEquals(test.isDaylightSavings(instant), false);
}
@BeforeMethod
public void setUp() {
TEST_2007_07_15 = LocalDate.of(2007, 7, 15);
LocalDate max = LocalDate.MAX;
LocalDate min = LocalDate.MIN;
MAX_VALID_EPOCHDAYS = max.toEpochDay();
MIN_VALID_EPOCHDAYS = min.toEpochDay();
MAX_DATE = max;
MIN_DATE = min;
MAX_INSTANT = max.atStartOfDay(ZoneOffset.UTC).toInstant();
MIN_INSTANT = min.atStartOfDay(ZoneOffset.UTC).toInstant();
}
@BeforeMethod
public void setUp() {
TEST_2007_07_15 = LocalDate.of(2007, 7, 15);
LocalDate max = LocalDate.MAX;
LocalDate min = LocalDate.MIN;
MAX_VALID_EPOCHDAYS = max.toEpochDay();
MIN_VALID_EPOCHDAYS = min.toEpochDay();
MAX_DATE = max;
MIN_DATE = min;
MAX_INSTANT = max.atStartOfDay(ZoneOffset.UTC).toInstant();
MIN_INSTANT = min.atStartOfDay(ZoneOffset.UTC).toInstant();
}
public void test_Paris_getOffsetInfo() {
ZoneId test = ZoneId.of("Europe/Paris");
checkOffset(test.getRules(), createLDT(2008, 1, 1), ZoneOffset.ofHours(1), 1);
checkOffset(test.getRules(), createLDT(2008, 2, 1), ZoneOffset.ofHours(1), 1);
checkOffset(test.getRules(), createLDT(2008, 3, 1), ZoneOffset.ofHours(1), 1);
checkOffset(test.getRules(), createLDT(2008, 4, 1), ZoneOffset.ofHours(2), 1);
checkOffset(test.getRules(), createLDT(2008, 5, 1), ZoneOffset.ofHours(2), 1);
checkOffset(test.getRules(), createLDT(2008, 6, 1), ZoneOffset.ofHours(2), 1);
checkOffset(test.getRules(), createLDT(2008, 7, 1), ZoneOffset.ofHours(2), 1);
checkOffset(test.getRules(), createLDT(2008, 8, 1), ZoneOffset.ofHours(2), 1);
checkOffset(test.getRules(), createLDT(2008, 9, 1), ZoneOffset.ofHours(2), 1);
checkOffset(test.getRules(), createLDT(2008, 10, 1), ZoneOffset.ofHours(2), 1);
checkOffset(test.getRules(), createLDT(2008, 11, 1), ZoneOffset.ofHours(1), 1);
checkOffset(test.getRules(), createLDT(2008, 12, 1), ZoneOffset.ofHours(1), 1);
}
@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));
}
private static Object handleSpecialAttributeTypes(Object obj) {
if (obj != null) {
if (obj instanceof ZonedDateTime) {
return ((ZonedDateTime) obj).toEpochSecond() * 1000;
} else if (obj instanceof LocalDate) {
return ((LocalDate) obj).toEpochDay() * (24 * 3600 * 1000);
} else if (obj instanceof LocalTime) {
return ((LocalTime) obj).get(ChronoField.MILLI_OF_DAY);
} else if (obj instanceof LocalDateTime) {
return ((LocalDateTime) obj).toInstant(ZoneOffset.UTC).toEpochMilli();
}
}
return obj;
}
@Test(expected=NullPointerException.class)
public void constructor_nullTime() throws Throwable {
Constructor<OffsetDateTime> con = OffsetDateTime.class.getDeclaredConstructor(LocalDateTime.class, ZoneOffset.class);
con.setAccessible(true);
try {
con.newInstance(null, OFFSET_PONE);
} catch (InvocationTargetException ex) {
throw ex.getCause();
}
}
public static long pack(Instant instant) {
if (instant == null) {
return missingValueIndicator();
}
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
return (pack(date, time));
}
private void doTestOffset(ZoneOffset offset, int hours, int minutes, int seconds) {
assertEquals(offset.getTotalSeconds(), hours * 60 * 60 + minutes * 60 + seconds);
final String id;
if (hours == 0 && minutes == 0 && seconds == 0) {
id = "Z";
} else {
String str = (hours < 0 || minutes < 0 || seconds < 0) ? "-" : "+";
str += Integer.toString(Math.abs(hours) + 100).substring(1);
str += ":";
str += Integer.toString(Math.abs(minutes) + 100).substring(1);
if (seconds != 0) {
str += ":";
str += Integer.toString(Math.abs(seconds) + 100).substring(1);
}
id = str;
}
assertEquals(offset.getId(), id);
assertEquals(offset, ZoneOffset.ofHoursMinutesSeconds(hours, minutes, seconds));
if (seconds == 0) {
assertEquals(offset, ZoneOffset.ofHoursMinutes(hours, minutes));
if (minutes == 0) {
assertEquals(offset, ZoneOffset.ofHours(hours));
}
}
assertEquals(ZoneOffset.of(id), offset);
assertEquals(offset.toString(), id);
}
OffsetTimeCodecTest() {
OffsetTime[] times = new OffsetTime[LocalTimeCodecTest.TIMES.length << 2];
for (int i = 0; i < LocalTimeCodecTest.TIMES.length; ++i) {
LocalTime time = LocalTimeCodecTest.TIMES[i];
times[i << 2] = OffsetTime.of(time, ZoneOffset.MIN);
times[(i << 2) + 1] = OffsetTime.of(time, ZoneOffset.of("+6"));
times[(i << 2) + 2] = OffsetTime.of(time, ZoneOffset.of("+10"));
times[(i << 2) + 3] = OffsetTime.of(time, ZoneOffset.MAX);
}
this.times = times;
}
@Test
public void test_parse_leapSecond() {
Instant expected = OffsetDateTime.of(1970, 2, 3, 23, 59, 59, 123456789, ZoneOffset.UTC).toInstant();
DateTimeFormatter f = new DateTimeFormatterBuilder().appendInstant(-1).toFormatter();
for (ResolverStyle style : ResolverStyle.values()) {
TemporalAccessor parsed = f.withResolverStyle(style).parse("1970-02-03T23:59:60.123456789Z");
assertEquals(parsed.query(Instant::from), expected);
assertEquals(parsed.query(DateTimeFormatter.parsedExcessDays()), Period.ZERO);
assertEquals(parsed.query(DateTimeFormatter.parsedLeapSecond()), Boolean.TRUE);
}
}
@Test(dataProvider="offsetPatterns")
public void test_appendOffset_format(String pattern, int h, int m, int s, String expected) throws Exception {
builder.appendOffset(pattern, "Z");
DateTimeFormatter f = builder.toFormatter();
ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(h, m, s);
assertEquals(f.format(offset), expected);
}