下面列出了怎么用java.time.LocalTime的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void test_minusHours_one() {
LocalDateTime t =TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate();
for (int i = 0; i < 50; i++) {
t = t.minusHours(1);
if (i % 24 == 0) {
d = d.minusDays(1);
}
assertEquals(t.toLocalDate(), d);
assertEquals(t.getHour(), (((-i + 23) % 24) + 24) % 24);
}
}
private Pair<Event,String> initEvent(List<TicketCategoryModification> categories, String displayName) {
String organizationName = UUID.randomUUID().toString();
String username = UUID.randomUUID().toString();
String eventName = UUID.randomUUID().toString();
organizationRepository.create(organizationName, "org", "[email protected]");
Organization organization = organizationRepository.findByName(organizationName).get();
userManager.insertUser(organization.getId(), username, "test", "test", "[email protected]", Role.OPERATOR, User.Type.INTERNAL);
Map<String, String> desc = new HashMap<>();
desc.put("en", "muh description");
desc.put("it", "muh description");
desc.put("de", "muh description");
EventModification em = new EventModification(null, Event.EventFormat.IN_PERSON, "url", "url", "url", "privacy", null, null,
eventName, displayName, organization.getId(),
"muh location",
"0.0", "0.0", ZoneId.systemDefault().getId(), desc,
new DateTimeModification(LocalDate.now().plusDays(5), LocalTime.now()),
new DateTimeModification(LocalDate.now().plusDays(5), LocalTime.now().plusHours(1)),
BigDecimal.TEN, "CHF", AVAILABLE_SEATS, BigDecimal.ONE, true, List.of(PaymentProxy.ON_SITE), categories, false, new LocationDescriptor("","","",""), 7, null, null, AlfioMetadata.empty());
eventManager.createEvent(em, username);
return Pair.of(eventManager.getSingleEvent(eventName, username), username);
}
@Test
@SuppressWarnings("unused")
public void now() {
// Warmup the TimeZone data so the following test does not include
// one-time initialization
LocalTime.now(Clock.systemDefaultZone());
long diff = Integer.MAX_VALUE;
for (int i = 0; i < 2; i++) {
LocalTime expected = LocalTime.now(Clock.systemDefaultZone());
LocalTime test = LocalTime.now();
diff = test.toNanoOfDay() - expected.toNanoOfDay();
// Normalize for wrap-around midnight
diff = Math.floorMod(NANOS_PER_DAY + diff, NANOS_PER_DAY);
if (diff < 100000000) {
break;
}
// A second iteration may be needed if the clock changed
// due to a DST change between the two calls to now.
}
assertTrue(diff < 100000000, // less than 0.1 sec
"LocalTime.now vs LocalTime.now(Clock.systemDefaultZone()) not close");
}
public EntityTypeSerializer()
{
// TODO A ton more types need to be added here
dataTypes.put( String.class.getName(), XMLSchema.STRING );
dataTypes.put( Integer.class.getName(), XMLSchema.INT );
dataTypes.put( Boolean.class.getName(), XMLSchema.BOOLEAN );
dataTypes.put( Byte.class.getName(), XMLSchema.BYTE );
dataTypes.put( BigDecimal.class.getName(), XMLSchema.DECIMAL );
dataTypes.put( Double.class.getName(), XMLSchema.DOUBLE );
dataTypes.put( Long.class.getName(), XMLSchema.LONG );
dataTypes.put( Short.class.getName(), XMLSchema.SHORT );
dataTypes.put( Instant.class.getName(), XMLSchema.LONG );
dataTypes.put( OffsetDateTime.class.getName(), XMLSchema.DATETIME );
dataTypes.put( ZonedDateTime.class.getName(), XMLSchema.DATETIME );
dataTypes.put( LocalDateTime.class.getName(), XMLSchema.DATETIME );
dataTypes.put( LocalDate.class.getName(), XMLSchema.DATE );
dataTypes.put( LocalTime.class.getName(), XMLSchema.TIME );
dataTypes.put( Duration.class.getName(), XMLSchema.DURATION );
dataTypes.put( Period.class.getName(), XMLSchema.DURATION );
}
/**
* Creates an instance defining the yearly rule to create transitions between two offsets.
*
* @param month the month of the month-day of the first day of the cutover week, not null
* @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that
* day or later, negative if the week is that day or earlier, counting from the last day of the month,
* from -28 to 31 excluding 0
* @param dayOfWeek the required day-of-week, null if the month-day should not be changed
* @param time the cutover time in the 'before' offset, not null
* @param timeEndOfDay whether the time is midnight at the end of day
* @param timeDefnition how to interpret the cutover
* @param standardOffset the standard offset in force at the cutover, not null
* @param offsetBefore the offset before the cutover, not null
* @param offsetAfter the offset after the cutover, not null
* @throws IllegalArgumentException if the day of month indicator is invalid
* @throws IllegalArgumentException if the end of day flag is true when the time is not midnight
*/
ZoneOffsetTransitionRule(
Month month,
int dayOfMonthIndicator,
DayOfWeek dayOfWeek,
LocalTime time,
boolean timeEndOfDay,
TimeDefinition timeDefnition,
ZoneOffset standardOffset,
ZoneOffset offsetBefore,
ZoneOffset offsetAfter) {
this.month = month;
this.dom = (byte) dayOfMonthIndicator;
this.dow = dayOfWeek;
this.time = time;
this.timeEndOfDay = timeEndOfDay;
this.timeDefinition = timeDefnition;
this.standardOffset = standardOffset;
this.offsetBefore = offsetBefore;
this.offsetAfter = offsetAfter;
}
@Test
public void test_minusMinutes_fromZero() {
LocalTime base = LocalTime.MIDNIGHT;
int hour = 22;
int min = 49;
for (int i = 70; i > -70; i--) {
LocalTime t = base.minusMinutes(i);
min++;
if (min == 60) {
hour++;
min = 0;
if (hour == 24) {
hour = 0;
}
}
assertEquals(t.getHour(), hour);
assertEquals(t.getMinute(), min);
}
}
@Test
public void test_getLong_TemporalField() {
OffsetDateTime test = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(12, 30, 40, 987654321), OFFSET_PONE);
assertEquals(test.getLong(ChronoField.YEAR), 2008);
assertEquals(test.getLong(ChronoField.MONTH_OF_YEAR), 6);
assertEquals(test.getLong(ChronoField.DAY_OF_MONTH), 30);
assertEquals(test.getLong(ChronoField.DAY_OF_WEEK), 1);
assertEquals(test.getLong(ChronoField.DAY_OF_YEAR), 182);
assertEquals(test.getLong(ChronoField.HOUR_OF_DAY), 12);
assertEquals(test.getLong(ChronoField.MINUTE_OF_HOUR), 30);
assertEquals(test.getLong(ChronoField.SECOND_OF_MINUTE), 40);
assertEquals(test.getLong(ChronoField.NANO_OF_SECOND), 987654321);
assertEquals(test.getLong(ChronoField.HOUR_OF_AMPM), 0);
assertEquals(test.getLong(ChronoField.AMPM_OF_DAY), 1);
assertEquals(test.getLong(ChronoField.INSTANT_SECONDS), test.toEpochSecond());
assertEquals(test.getLong(ChronoField.OFFSET_SECONDS), 3600);
}
@Override
@FxThread
public void notifyClosed() {
FX_EVENT_MANAGER.removeEventHandler(FileChangedEvent.EVENT_TYPE, getFileChangedHandler());
final Duration duration = Duration.between(showedTime, LocalTime.now());
final int seconds = (int) duration.getSeconds();
final EditorDescription description = getDescription();
GAnalytics.sendEvent(GAEvent.Category.EDITOR, GAEvent.Action.EDITOR_CLOSED,
description.getEditorId() + "/" + getFileName());
GAnalytics.sendTiming(GAEvent.Category.EDITOR, GAEvent.Label.WORKING_ON_AN_EDITOR,
seconds, description.getEditorId());
}
@Test
public void test_plusMinutes_one() {
LocalDateTime t = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
LocalDate d = t.toLocalDate();
int hour = 0;
int min = 0;
for (int i = 0; i < 70; i++) {
t = t.plusMinutes(1);
min++;
if (min == 60) {
hour++;
min = 0;
}
assertEquals(t.toLocalDate(), d);
assertEquals(t.getHour(), hour);
assertEquals(t.getMinute(), min);
}
}
private WorkSchedule createPostalService() throws Exception {
// United States Postal Service
WorkSchedule schedule = new WorkSchedule("USPS", "Six 9 hr shifts, rotating every 42 days");
// shift, start at 08:00 for 9 hours
Shift day = schedule.createShift("Day", "day shift", LocalTime.of(8, 0, 0), Duration.ofHours(9));
Rotation rotation = schedule.createRotation("Day", "Day");
rotation.addSegment(day, 3, 7);
rotation.addSegment(day, 1, 7);
rotation.addSegment(day, 1, 7);
rotation.addSegment(day, 1, 7);
rotation.addSegment(day, 1, 7);
LocalDate rotationStart = LocalDate.of(2017, 1, 27);
// day teams
schedule.createTeam("Team A", "A team", rotation, rotationStart);
schedule.createTeam("Team B", "B team", rotation, rotationStart.minusDays(7));
schedule.createTeam("Team C", "C team", rotation, rotationStart.minusDays(14));
schedule.createTeam("Team D", "D team", rotation, rotationStart.minusDays(21));
schedule.createTeam("Team E", "E team", rotation, rotationStart.minusDays(28));
schedule.createTeam("Team F", "F team", rotation, rotationStart.minusDays(35));
return schedule;
}
@Test(dataProvider="calendars")
public void test_badPlusTemporalUnitChrono(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
for (Chronology[] clist : data_of_calendars()) {
Chronology chrono2 = clist[0];
ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
TemporalUnit adjuster = new FixedTemporalUnit(czdt2);
if (chrono != chrono2) {
try {
czdt.plus(1, adjuster);
Assert.fail("TemporalUnit.doPlus plus should have thrown a ClassCastException, " + czdt
+ " can not be cast to " + czdt2);
} catch (ClassCastException cce) {
// Expected exception; not an error
}
} else {
// Same chronology,
ChronoZonedDateTime<?> result = czdt.plus(1, adjuster);
assertEquals(result, czdt2, "WithAdjuster failed to replace date");
}
}
}
/**
* Parse the RFC3164 date format. This is trickier than it sounds because this
* format does not specify a year so we get weird edge cases at year
* boundaries. This implementation tries to "do what I mean".
* @param ts RFC3164-compatible timestamp to be parsed
* @return Typical (for Java) milliseconds since the UNIX epoch
*/
public static long parseRfc3164Time(String ts) throws OnRecordErrorException {
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
ts = TWO_SPACES.matcher(ts).replaceFirst(" ");
LocalDateTime date;
try {
MonthDay monthDay = MonthDay.parse(ts, rfc3164Format);
LocalTime time = LocalTime.parse(ts, rfc3164Format);
// this is overly complicated because of the way Java 8 Time API works, as compared to Joda
// essentially, we just want to pull year out of "now" and set all other fields based on
// what was parsed
date = now;
// zero out millis since we aren't actually parsing those
date = date.with(ChronoField.MILLI_OF_SECOND, 0);
// set month and day of month from parsed
date = date.withMonth(monthDay.getMonthValue()).withDayOfMonth(monthDay.getDayOfMonth());
// set time fields from parsed
date = date.withHour(time.getHour()).withMinute(time.getMinute()).withSecond(time.getSecond());
} catch (DateTimeParseException e) {
throw new OnRecordErrorException(Errors.SYSLOG_10, ts, e);
}
// The RFC3164 is a bit weird date format - it contains day and month, but no year. So we have to somehow guess
// the year. The current logic is to provide a sliding window - going 11 months to the past and 1 month to the
// future. If the message is outside of this window, it will have incorrectly guessed year. We go 11 months to the
// past as we're expecting that more messages will be from the past (syslog usually contains historical data).
LocalDateTime fixed = date;
if (fixed.isAfter(now) && fixed.minusMonths(1).isAfter(now)) {
fixed = date.withYear(year - 1);
} else if (fixed.isBefore(now) && fixed.plusMonths(11).isBefore(now)) {
fixed = date.withYear(year + 1);
}
date = fixed;
return date.toInstant(ZoneOffset.UTC).toEpochMilli();
}
@Override
public LocalTime parse(String value) {
if (isMissing(value)) {
return null;
}
String paddedValue = Strings.padStart(value, 4, '0');
return LocalTime.parse(paddedValue, parserFormatter);
}
@Test(dataProvider="calendars")
public void test_from_TemporalAccessor(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoLocalDate date = chrono.date(refDate);
ChronoLocalDate test1 = ChronoLocalDate.from(date);
assertEquals(test1, date);
ChronoLocalDate test2 = ChronoLocalDate.from(date.atTime(LocalTime.of(12, 30)));
assertEquals(test2, date);
ChronoLocalDate test3 = ChronoLocalDate.from(date.atTime(LocalTime.of(12, 30)).atZone(ZoneOffset.UTC));
assertEquals(test3, date);
}
@Test
public void test_Instant_zonedDateTime() {
OffsetDateTime offsetDateTime = OffsetDateTime.of(2012, 2, 29, 2, 7, 1, 1, OFFSET_PTWO);
ZonedDateTime zonedDateTime = ZonedDateTime.of(2012, 2, 29, 2, 7, 1, 1, ZONE_PARIS);
ChronoZonedDateTime<MinguoDate> result = MinguoChronology.INSTANCE.zonedDateTime(offsetDateTime.toInstant(), offsetDateTime.getOffset());
assertEquals(result.toLocalDate(), MinguoChronology.INSTANCE.date(MinguoEra.ROC, 2012 - YDIFF, 2, 29));
assertEquals(result.toLocalTime(), LocalTime.of(2, 7, 1, 1));
result = MinguoChronology.INSTANCE.zonedDateTime(zonedDateTime.toInstant(), zonedDateTime.getOffset());
assertEquals(result.toLocalDate(), MinguoChronology.INSTANCE.date(MinguoEra.ROC, 2012 - YDIFF, 2, 29));
assertEquals(result.toLocalTime(), LocalTime.of(2, 7, 1, 1));
}
@Test
public void test_plusHours_one() {
LocalTime t = LocalTime.MIDNIGHT;
for (int i = 0; i < 50; i++) {
t = t.plusHours(1);
assertEquals(t.getHour(), (i + 1) % 24);
}
}
@Test
public void test_plusHours_one() {
LocalTime t = LocalTime.MIDNIGHT;
for (int i = 0; i < 50; i++) {
t = t.plusHours(1);
assertEquals(t.getHour(), (i + 1) % 24);
}
}
@Test
public void test_with_longTemporalField_clockHourOfAmPm() {
for (int i = 1; i <= 12; i++) {
LocalTime test = TEST_12_30_40_987654321.with(CLOCK_HOUR_OF_AMPM, i);
assertEquals(test.get(CLOCK_HOUR_OF_AMPM), i);
assertEquals(test.get(AMPM_OF_DAY), TEST_12_30_40_987654321.get(AMPM_OF_DAY));
assertEquals(test.get(MINUTE_OF_HOUR), TEST_12_30_40_987654321.get(MINUTE_OF_HOUR));
assertEquals(test.get(SECOND_OF_MINUTE), TEST_12_30_40_987654321.get(SECOND_OF_MINUTE));
assertEquals(test.get(NANO_OF_SECOND), TEST_12_30_40_987654321.get(NANO_OF_SECOND));
}
}
@Test(dataProvider="minusSeconds_fromZero")
public void test_minusSeconds_fromZero(int seconds, LocalDate date, int hour, int min, int sec) {
LocalDateTime base = TEST_2007_07_15_12_30_40_987654321.with(LocalTime.MIDNIGHT);
LocalDateTime t = base.minusSeconds(seconds);
assertEquals(date, t.toLocalDate());
assertEquals(hour, t.getHour());
assertEquals(min, t.getMinute());
assertEquals(sec, t.getSecond());
}
@Test
public void test_toNanoOfDay_fromNanoOfDay_symmetry() {
LocalTime t = LocalTime.of(0, 0);
for (int i = 0; i < 1000000; i++) {
assertEquals(LocalTime.ofNanoOfDay(t.toNanoOfDay()), t);
t = t.plusNanos(1);
}
t = LocalTime.of(0, 0);
for (int i = 1; i <= 1000000; i++) {
t = t.minusNanos(1);
assertEquals(LocalTime.ofNanoOfDay(t.toNanoOfDay()), t);
}
}
protected String format(Framework.Mapping<?> mapping) {
if (mapping.meta().targetType == Byte.class)
return "byte";
if (mapping.meta().targetType == Byte[].class)
return "binary";
if (mapping.meta().targetType == LocalDate.class)
return "date";
if (mapping.meta().targetType == LocalDateTime.class)
return "date-time";
if (mapping.meta().targetType == LocalTime.class)
return "time";
if (mapping.meta().targetType == UUID.class)
return "uuid";
if (mapping.meta().targetType == URL.class)
return "url";
if (mapping.meta().targetType == String.class && findConstraint(mapping, "email") != null)
return "email";
if (mapping.meta().targetType == Integer.class)
return "int32";
if (mapping.meta().targetType == Long.class || mapping.meta().targetType == BigInteger.class)
return "int64";
if (mapping.meta().targetType == Float.class)
return "float";
if (mapping.meta().targetType == Double.class || mapping.meta().targetType == BigDecimal.class) {
return "double";
}
return attach(mapping).format();
}
@Test
public void test_toNanoOfDay() {
LocalTime t = LocalTime.of(0, 0);
for (int i = 0; i < 1000000; i++) {
assertEquals(t.toNanoOfDay(), i);
t = t.plusNanos(1);
}
t = LocalTime.of(0, 0);
for (int i = 1; i <= 1000000; i++) {
t = t.minusNanos(1);
assertEquals(t.toNanoOfDay(), 24 * 60 * 60 * 1000000000L - i);
}
}
private void updateCheckConflict(LocalTime timeToSet, Period periodToSet) {
if (time != null) {
if (time.equals(timeToSet) == false) {
throw new DateTimeException("Conflict found: Fields resolved to different times: " + time + " " + timeToSet);
}
if (excessDays.isZero() == false && periodToSet.isZero() == false && excessDays.equals(periodToSet) == false) {
throw new DateTimeException("Conflict found: Fields resolved to different excess periods: " + excessDays + " " + periodToSet);
} else {
excessDays = periodToSet;
}
} else {
time = timeToSet;
excessDays = periodToSet;
}
}
void HijrahExample1() {
HijrahDate hd2 = HijrahChronology.INSTANCE.date(1200, 1, 1);
ChronoLocalDateTime<HijrahDate> hdt = hd2.atTime(LocalTime.MIDNIGHT);
ChronoZonedDateTime<HijrahDate> zhdt = hdt.atZone(ZoneId.of("GMT"));
HijrahDate hd3 = zhdt.toLocalDate();
ChronoLocalDateTime<HijrahDate> hdt2 = zhdt.toLocalDateTime();
HijrahDate hd4 = hdt2.toLocalDate();
HijrahDate hd5 = next(hd2);
}
private void testLocalTime(LocalTime time, String expectedPattern) {
ResourceEntity<PTime> re = new RootResourceEntity<>(timeEntity, null);
ResourceEntityUtils.appendAttribute(re, "time", LocalTime.class);
PTime o = new PTime();
o.setTime(time);
String timeString = DateTimeFormatter.ofPattern(expectedPattern).format(time);
assertEquals("{\"data\":[{\"time\":\"" + timeString + "\"}],\"total\":1}", toJson(o, re));
}
@Test(dataProvider = "fields")
public void test_WBY_isSupportedBy(TemporalField weekField, TemporalField yearField) {
assertEquals(yearField.isSupportedBy(LocalTime.NOON), false);
assertEquals(yearField.isSupportedBy(MonthDay.of(2, 1)), false);
assertEquals(yearField.isSupportedBy(LocalDate.MIN), true);
assertEquals(yearField.isSupportedBy(OffsetDateTime.MAX), true);
}
@Test
public void test_with_adjustment() {
final OffsetDateTime sample = OffsetDateTime.of(LocalDate.of(2012, 3, 4), LocalTime.of(23, 5), OFFSET_PONE);
TemporalAdjuster adjuster = new TemporalAdjuster() {
@Override
public Temporal adjustInto(Temporal dateTime) {
return sample;
}
};
assertEquals(TEST_2008_6_30_11_30_59_000000500.with(adjuster), sample);
}
@DataProvider(name="unitAndTemporal")
Object[][] data_unitAndTemporal() {
return new Object[][] {
{CENTURIES, LocalDate.of(2000, 1, 10), true, 1, LocalDate.of(2100, 1, 10)},
{DECADES, LocalDate.of(2000, 1, 10), true, 1, LocalDate.of(2010, 1, 10)},
{YEARS, LocalDate.of(2000, 1, 10), true, 1, LocalDate.of(2001, 1, 10)},
{MONTHS, LocalDate.of(2000, 1, 10), true, 1, LocalDate.of(2000, 2, 10)},
{WEEKS, LocalDate.of(2000, 1, 10), true, 1, LocalDate.of(2000, 1, 17)},
{DAYS, LocalDate.of(2000, 1, 10), true, 1, LocalDate.of(2000, 1, 11)},
{HALF_DAYS, LocalTime.of(1, 2, 3, 400), true, 1, LocalTime.of(13, 2, 3, 400)},
{HOURS, LocalTime.of(1, 2, 3, 400), true, 1, LocalTime.of(2, 2, 3, 400)},
{MINUTES, LocalTime.of(1, 2, 3, 400), true, 1, LocalTime.of(1, 3, 3, 400)},
{SECONDS, LocalTime.of(1, 2, 3, 400), true, 1, LocalTime.of(1, 2, 4, 400)},
{MICROS, LocalTime.of(1, 2, 3, 400), true, 1, LocalTime.of(1, 2, 3, 1000 + 400)},
{MILLIS, LocalTime.of(1, 2, 3, 400), true, 1, LocalTime.of(1, 2, 3, 1000*1000 + 400)},
{NANOS, LocalTime.of(1, 2, 3, 400), true, 1, LocalTime.of(1, 2, 3, 1 + 400)},
{CENTURIES, LocalTime.of(1, 2, 3, 400), false, 1, null},
{DECADES, LocalTime.of(1, 2, 3, 400), false, 1, null},
{YEARS, LocalTime.of(1, 2, 3, 400), false, 1, null},
{MONTHS, LocalTime.of(1, 2, 3, 400), false, 1, null},
{WEEKS, LocalTime.of(1, 2, 3, 400), false, 1, null},
{DAYS, LocalTime.of(1, 2, 3, 400), false, 1, null},
{HALF_DAYS, LocalDate.of(2000, 2, 29), false, 1, null},
{HOURS, LocalDate.of(2000, 2, 29), false, 1, null},
{MINUTES, LocalDate.of(2000, 2, 29), false, 1, null},
{SECONDS, LocalDate.of(2000, 2, 29), false, 1, null},
{MICROS, LocalDate.of(2000, 2, 29), false, 1, null},
{MILLIS, LocalDate.of(2000, 2, 29), false, 1, null},
{NANOS, LocalDate.of(2000, 2, 29), false, 1, null},
};
}
@Test(dataProvider="sampleTimes")
public void test_get(int h, int m, int s, int ns) {
LocalTime a = LocalTime.of(h, m, s, ns);
assertEquals(a.getHour(), h);
assertEquals(a.getMinute(), m);
assertEquals(a.getSecond(), s);
assertEquals(a.getNano(), ns);
}
/**
* Check if a value in the TOML document is a {@link LocalTime}.
*
* @param path The key path.
* @return {@code true} if the value can be obtained as a {@link LocalTime}.
*/
default boolean isLocalTime(List<String> path) {
Object value;
try {
value = get(path);
} catch (TomlInvalidTypeException e) {
return false;
}
return value instanceof LocalTime;
}