下面列出了怎么用java.time.LocalDateTime的API类实例代码及写法,或者点击链接到github查看源代码。
@DataProvider(name="epochSecond")
Object[][] provider_toEpochSecond() {
return new Object[][] {
{LocalDate.of(1858, 11, 17).toEpochSecond(LocalTime.MIDNIGHT, OFFSET_PONE), -3506720400L},
{LocalDate.of(1, 1, 1).toEpochSecond(LocalTime.NOON, OFFSET_PONE), -62135557200L},
{LocalDate.of(1995, 9, 27).toEpochSecond(LocalTime.of(5, 30), OFFSET_PTWO), 812172600L},
{LocalDate.of(1970, 1, 1).toEpochSecond(LocalTime.MIDNIGHT, OFFSET_MTWO), 7200L},
{LocalDate.of(-1, 12, 31).toEpochSecond(LocalTime.NOON, OFFSET_PONE), -62167266000L},
{LocalDate.of(1, 1, 1).toEpochSecond(LocalTime.MIDNIGHT, OFFSET_PONE),
Instant.ofEpochSecond(-62135600400L).getEpochSecond()},
{LocalDate.of(1995, 9, 27).toEpochSecond(LocalTime.NOON, OFFSET_PTWO),
Instant.ofEpochSecond(812196000L).getEpochSecond()},
{LocalDate.of(1995, 9, 27).toEpochSecond(LocalTime.of(5, 30), OFFSET_MTWO),
LocalDateTime.of(1995, 9, 27, 5, 30).toEpochSecond(OFFSET_MTWO)},
};
}
@Test
public void testDate() {
System.out.println(DateUtil.getCurrentYear());
System.out.println(DateUtil.getCurrentYearMonth());
System.out.println(DateUtil.getCurrentDate());
System.out.println(DateUtil.getCurrentDateShort());
System.out.println(DateUtil.getCurrentDate("yyyy/MM/dd"));
System.out.println(DateUtil.getCurrentDateTime());
System.out.println(DateUtil.getCurrentDateTimeShort());
System.out.println(DateUtil.getCurrentDateTime("yyyy/MM/dd HH:mm:ss"));
System.out.println(DateUtil.getTimestamp());
System.out.println(DateUtil.intervalDays(LocalDate.of(2020, 5, 7), LocalDate.of(2020, 5, 9)));
System.out.println(DateUtil.intervalHours(LocalDateTime.of(2020, 5, 7, 12, 30, 10), LocalDateTime.of(2020, 5, 7, 13, 30, 12)));
System.out.println(DateUtil.intervalMinutes(LocalDateTime.of(2020, 5, 7, 12, 30, 10), LocalDateTime.of(2020, 5, 7, 13, 30, 12)));
System.out.println(DateUtil.intervalMillis(LocalDateTime.of(2020, 5, 7, 12, 30, 10), LocalDateTime.of(2020, 5, 7, 13, 30, 12)));
}
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 );
}
@Test
@Deployment(resources = { "org/flowable/rest/service/api/runtime/ProcessInstanceVariableResourceTest.testProcess.bpmn20.xml" })
public void testGetProcessInstanceLocalDateTimeVariable() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
LocalDateTime now = LocalDateTime.now();
LocalDateTime nowWithoutNanos = now.truncatedTo(ChronoUnit.MILLIS);
runtimeService.setVariable(processInstance.getId(), "variable", now);
CloseableHttpResponse response = executeRequest(
new HttpGet(
SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_VARIABLE, processInstance.getId(), "variable")),
HttpStatus.SC_OK);
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertThat(responseNode).isNotNull();
assertThatJson(responseNode)
.when(Option.IGNORING_EXTRA_FIELDS)
.isEqualTo("{"
+ " name: 'variable',"
+ " type: 'localDateTime',"
+ " value: '" + nowWithoutNanos.toString() + "'"
+ "}");
}
public void test_Paris_getOffsetInfo_gap() {
ZoneRules test = europeParis();
final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0);
ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, GAP);
assertEquals(trans.isGap(), true);
assertEquals(trans.isOverlap(), false);
assertEquals(trans.getOffsetBefore(), OFFSET_PONE);
assertEquals(trans.getOffsetAfter(), OFFSET_PTWO);
assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC));
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-30T02:00+01:00 to +02:00]");
assertFalse(trans.equals(null));
assertFalse(trans.equals(OFFSET_PONE));
assertTrue(trans.equals(trans));
final ZoneOffsetTransition otherTrans = test.getTransition(dateTime);
assertTrue(trans.equals(otherTrans));
assertEquals(trans.hashCode(), otherTrans.hashCode());
}
private String buildMessage(List<AlertRecord> alertRecordList) {
AlertRecord firstRecord = alertRecordList.get(0);
StringBuffer message = new StringBuffer();
message.append("Group Name: ").append(firstRecord.getGroupName()).append(NEW_LINE)
.append("Cluster Name: ").append(firstRecord.getClusterName()).append(NEW_LINE);
alertRecordList.forEach(alertRecord -> {
message.append("Redis Node: ").append(alertRecord.getRedisNode()).append(NEW_LINE)
.append("Alert Rule: ").append(alertRecord.getAlertRule()).append(NEW_LINE)
.append("Actual Value: ").append(alertRecord.getActualData()).append(NEW_LINE);
String ruleInfo = alertRecord.getRuleInfo();
if (!Strings.isNullOrEmpty(ruleInfo)) {
message.append("Rule Info: ").append(alertRecord.getRuleInfo()).append(NEW_LINE);
}
message.append(NEW_LINE);
});
message.append("Time: ").append(LocalDateTime.now().format(TIME_FORMATTER));
return message.toString();
}
@DataProvider(name="adjustInto")
Object[][] data_adjustInto() {
return new Object[][]{
{OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), OffsetDateTime.of(2012, 3, 4, 1, 1, 1, 100, ZoneOffset.UTC), OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), null},
{OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), OffsetDateTime.MAX, OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), null},
{OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), OffsetDateTime.MIN, OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), null},
{OffsetDateTime.MAX, OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), OffsetDateTime.of(OffsetDateTime.MAX.toLocalDateTime(), ZoneOffset.ofHours(-18)), null},
{OffsetDateTime.MIN, OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), OffsetDateTime.of(OffsetDateTime.MIN.toLocalDateTime(), ZoneOffset.ofHours(18)), null},
{OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE),
ZonedDateTime.of(2012, 3, 4, 1, 1, 1, 100, ZONE_GAZA), ZonedDateTime.of(2012, 3, 4, 23, 5, 0, 0, ZONE_GAZA), null},
{OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), LocalDateTime.of(2012, 3, 4, 1, 1, 1, 100), null, DateTimeException.class},
{OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), LocalDate.of(2210, 2, 2), null, DateTimeException.class},
{OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), LocalTime.of(22, 3, 0), null, DateTimeException.class},
{OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), OffsetTime.of(22, 3, 0, 0, ZoneOffset.UTC), null, DateTimeException.class},
{OffsetDateTime.of(2012, 3, 4, 23, 5, 0, 0, OFFSET_PONE), null, null, NullPointerException.class},
};
}
private void testDateTimeSchema() {
Date date = new Date();
TestMgr.check(date.getTime(), dateTimeSchemaInf.getDate(date).getTime());
TestMgr.check(date.getTime(), dateTimeSchemaInf.getDatePath(date).getTime());
TestMgr.check(date.getTime(), dateTimeSchemaInf.postDate(date).getTime());
LocalDate localDate = LocalDate.of(2020, 2, 1);
TestMgr.check(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
dateTimeSchemaInf.getLocalDate(localDate).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
TestMgr.check(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
dateTimeSchemaInf.getLocalDatePath(localDate).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
TestMgr.check(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
dateTimeSchemaInf.postLocalDate(localDate).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
LocalDateTime localDateTime = LocalDateTime.of(2020, 2, 1, 23, 23, 30, 333);
TestMgr.check(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")),
dateTimeSchemaInf.getLocalDateTime(localDateTime)
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")));
TestMgr.check(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")),
dateTimeSchemaInf.getLocalDateTimePath(localDateTime)
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")));
TestMgr.check(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")),
dateTimeSchemaInf.postLocalDateTime(localDateTime)
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")));
}
private LocalWeatherData createLocalWeatherData(final Station station, final LocalDateTime measuredTime) {
final LocalWeatherData data = new LocalWeatherData();
data.dateTime = DateUtilities.from(measuredTime, ZoneOffset.UTC);
data.station = station;
data.skyCondition = "CLR";
data.temperature = 22.0f;
data.stationPressure = 42.12f;
data.windSpeed = 5.0f;
return data;
}
@Test
public void test_with_adjuster_LocalDate_retainOffset2() {
ZoneId newYork = ZoneId.of("America/New_York");
LocalDateTime ldt = LocalDateTime.of(2008, 11, 3, 1, 30);
ZonedDateTime base = ZonedDateTime.of(ldt, newYork);
assertEquals(base.getOffset(), ZoneOffset.ofHours(-5));
ZonedDateTime test = base.with(LocalDate.of(2008, 11, 2));
assertEquals(test.getOffset(), ZoneOffset.ofHours(-5));
}
public SimulationResult(SimulationResult result) {
super(result.getName(), new Result(result.getResult().getStatus(),result.getResultDuration(),result.getResult().getError()) ,LocalDateTime.from(result.getStart()), LocalDateTime.from(result.getStop()));
for (GroupResult gr: result.getChildResults())
{
totalRan += gr.getChildResults().size();
GroupResult ngr = new GroupResult(gr);
childResults.add(ngr);
}
this.updateStatus(childResults);
}
@Builder
public RoleOrg(Long id, LocalDateTime createTime, Long createUser,
Long roleId, Long orgId) {
this.id = id;
this.createTime = createTime;
this.createUser = createUser;
this.roleId = roleId;
this.orgId = orgId;
}
/**
* Converts this {@code Timestamp} object to a {@code LocalDateTime}.
* <p>
* The conversion creates a {@code LocalDateTime} that represents the
* same year, month, day of month, hours, minutes, seconds and nanos
* date-time value as this {@code Timestamp} in the local time zone.
*
* @return a {@code LocalDateTime} object representing the same date-time value
* @since 1.8
*/
@SuppressWarnings("deprecation")
public LocalDateTime toLocalDateTime() {
return LocalDateTime.of(getYear() + 1900,
getMonth() + 1,
getDate(),
getHours(),
getMinutes(),
getSeconds(),
getNanos());
}
@Override
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
//1. code is required
String code = params.getFirst("code");
if (code == null || "".equals(code)) {
throw new WebApplicationException("invalid_grant");
}
AuthorizationCode authorizationCode = entityManager.find(AuthorizationCode.class, code);
if (!authorizationCode.getExpirationDate().isAfter(LocalDateTime.now())) {
throw new WebApplicationException("code Expired !");
}
String redirectUri = params.getFirst("redirect_uri");
//redirecturi match
if (authorizationCode.getRedirectUri() != null && !authorizationCode.getRedirectUri().equals(redirectUri)) {
//redirectUri params should be the same as the requested redirectUri.
throw new WebApplicationException("invalid_grant");
}
//client match
if (!clientId.equals(authorizationCode.getClientId())) {
throw new WebApplicationException("invalid_grant");
}
//3. JWT Payload or claims
String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
return Json.createObjectBuilder()
.add("token_type", "Bearer")
.add("access_token", accessToken)
.add("expires_in", expiresInMin * 60)
.add("scope", authorizationCode.getApprovedScopes())
.add("refresh_token", refreshToken)
.build();
}
public static String convertValue(String type, String value) throws AMLException
{
Class<?> clazz = getClass(type);
if (clazz == null) {
throw new AMLException("Invalid type: " + type);
} else if (clazz.equals(Object.class) || clazz.equals(LocalDateTime.class) || clazz.equals(LocalDate.class)
|| clazz.equals(LocalTime.class)) {
throw new AMLException("Cannot convert " + clazz.getSimpleName());
}
return ObjectUtils.defaultIfNull(TypeConverter.convert(clazz, value), value);
}
@Test
public void testDeserializationAsTimestamp04Milliseconds02() throws Exception
{
ObjectReader r = READER
.without(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS);
LocalDateTime value = r.readValue("[2005,11,5,22,31,5,829]");
LocalDateTime time = LocalDateTime.of(2005, Month.NOVEMBER, 5, 22, 31, 5, 829000000);
assertEquals("The value is not correct.", time, value);
}
public DateTimeColumn asLocalDateTimeColumn(ZoneId zone) {
LocalDateTime[] output = new LocalDateTime[data.size()];
for (int i = 0; i < data.size(); i++) {
Instant instant = PackedInstant.asInstant(data.getLong(i));
if (instant == null) {
output[i] = null;
} else {
output[i] = LocalDateTime.ofInstant(instant, zone);
}
}
return DateTimeColumn.create(name(), output);
}
public static LocalDateTime parseLocalDateTime(String string) {
try {
return LocalDateTime.parse(string, DATE_TIME_FORMATTER);
} catch (DateTimeParseException e) {
return LocalDateTime.parse(string);
}
}
@Builder
public Station(Long id, LocalDateTime createTime, Long createUser, LocalDateTime updateTime, Long updateUser,
String name, RemoteData<Long, Org> orgId, Boolean status, String describe) {
this.id = id;
this.createTime = createTime;
this.createUser = createUser;
this.updateTime = updateTime;
this.updateUser = updateUser;
this.name = name;
this.org = orgId;
this.status = status;
this.describe = describe;
}
/**
* Parse date string.
*
* @param date the date
* @return the string
*/
public static String parseDate(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
return formaterLocalDateTime(localDateTime);
}
@Test
public void testDeserializationAsEmptyArrayEnabled() throws Throwable
{
LocalDateTime value = READER
.with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
.with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT)
.readValue("[]");
assertNull(value);
}
private Order newOrder() {
final Order order = new Order();
order.setId(1L);
order.setDate(LocalDateTime.now().minusHours(2));
order.setStatus(OrderStatus.SHIPPED);
final ShoppingCart cart = mockShoppingCart.getShoppingCart();
order.setSelections(cart.getSelections());
order.setPrice(cart.getPrice());
return order;
}
@Override
public final void encodeBinary(final LocalDateTime value, final BufferWriter b) {
final Instant instant = value.atOffset(ZoneOffset.UTC).toInstant();
final long seconds = instant.getEpochSecond();
final long micros = instant.getLong(ChronoField.MICRO_OF_SECOND) + (seconds * 1000000);
b.writeLong(micros - POSTGRES_EPOCH_MICROS);
}
@Test
public void test_minus_TemporalAmount_Duration() {
Duration duration = Duration.ofSeconds(4L * 60 * 60 + 5L * 60 + 6L);
ZonedDateTime t = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 12, 30, 59, 500), ZONE_0100);
ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 8, 25, 53, 500), ZONE_0100);
assertEquals(t.minus(duration), expected);
}
@Test
@UseDataProvider("data_print")
public void test_print(LocalDateTime ldt, ZoneId zone, String expected) {
ZonedDateTime zdt = ldt.atZone(zone);
builder.appendZoneId();
String output = builder.toFormatter().format(zdt);
assertEquals(output, expected);
}
/**
* date转localDateTime并减一定的天数
*
* @param date
* @return
*/
public static LocalDateTime dateToLocalDateTimeMiusDay(Date date, int dayNum) {
if (date == null) {
return null;
}
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
return instant.atZone(zoneId).toLocalDateTime().minusDays(dayNum);
}
public PoloniexLendingHistory(String id, String currency, BigDecimal rate, BigDecimal amount, BigDecimal duration, BigDecimal interest, BigDecimal fee, BigDecimal earned, LocalDateTime open, LocalDateTime close)
{
this.id = id;
this.currency = currency;
this.rate = rate;
this.amount = amount;
this.duration = duration;
this.interest = interest;
this.fee = fee;
this.earned = earned;
this.open = open;
this.close = close;
}
@Before
public void setUp(){
ArticleComment articleComment = repository.findTopByOrderByIdAsc().get();
LocalDateTime localDateTime = DateUtils.dateToLocalDateTime(new ObjectId(articleComment.getId()).getDate());
Long hours = ChronoUnit.MINUTES.between(localDateTime, LocalDateTime.now());
LocalDateTime randomDate = localDateTime.plusMinutes(new Random().nextInt((int) (hours + 1)));
randomArticleComment = repository.findTopByIdLessThanEqualOrderByIdDesc(new ObjectId(DateUtils.localDateTimeToDate(randomDate))).get();
}
@Test(expectedExceptions=DateTimeException.class)
public void test_minus_TemporalAmount_invalidTooLarge() {
MockSimplePeriod period = MockSimplePeriod.of(-1, YEARS);
LocalDateTime.of(Year.MAX_VALUE, 1, 1, 0, 0).minus(period);
}
public Criteria andUpdateTimeNotEqualTo(LocalDateTime value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}