下面列出了怎么用org.joda.time.LocalTime的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void convert() throws Exception {
String dateString = "06/27/2017 12:30";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm");
Date date = df.parse(dateString);
LocalTime localTime = (LocalTime) converter.convert(date, TypeToken.of(LocalTime.class));
assertEquals(12, localTime.getHourOfDay());
assertEquals(30, localTime.getMinuteOfHour());
LocalDate localDate = (LocalDate) converter.convert(date, TypeToken.of(LocalDate.class));
assertEquals(2017, localDate.getYear());
assertEquals(6, localDate.getMonthOfYear());
assertEquals(27, localDate.getDayOfMonth());
LocalDateTime localDateTime = (LocalDateTime) converter.convert(date, TypeToken.of(LocalDateTime.class));
assertEquals(12, localDateTime.getHourOfDay());
assertEquals(30, localDateTime.getMinuteOfHour());
assertEquals(2017, localDateTime.getYear());
assertEquals(6, localDateTime.getMonthOfYear());
assertEquals(27, localDateTime.getDayOfMonth());
}
/**
* Get the cost for the call based on the type, duration and time period of
* the call.
* @param call The call to have its cost calculated, it remains unchanged.
* @return The cost of the call
*/
public double getCallCost(Call call) {
int dayOfWeek = call.getTime().getStart().getDayOfWeek();
int duration = call.getTime().toDuration().toStandardMinutes().getMinutes();
LocalTime startTime = call.getTime().getStart().toLocalTime();
Map<String, Object> params = (Map<String, Object>) outgoingCallParams.get(call.getType());
String callCostParam;
if ((dayOfWeek == 1 || dayOfWeek == 7) ||
(startTime.compareTo(offPeakStart) >= 0
&& startTime.compareTo(offPeakEnd) <= 0)) {
callCostParam = "callOPCost";
} else {
callCostParam = "callCost";
}
long cost = (Long) params.get(callCostParam);
return duration * cost;
}
public static User generateRandomUser(Random rnd) {
return new User(
generateRandomString(rnd, 50),
rnd.nextBoolean() ? null : rnd.nextInt(),
rnd.nextBoolean() ? null : generateRandomString(rnd, 6),
rnd.nextBoolean() ? null : rnd.nextLong(),
rnd.nextDouble(),
null,
rnd.nextBoolean(),
generateRandomStringList(rnd, 20, 30),
generateRandomBooleanList(rnd, 20),
rnd.nextBoolean() ? null : generateRandomStringList(rnd, 20, 20),
generateRandomColor(rnd),
new HashMap<>(),
generateRandomFixed16(rnd),
generateRandomUnion(rnd),
generateRandomAddress(rnd),
generateRandomBytes(rnd),
LocalDate.parse("2014-03-01"),
LocalTime.parse("12:12:12"),
123456,
DateTime.parse("2014-03-01T12:12:12.321Z"),
123456L,
ByteBuffer.wrap(BigDecimal.valueOf(2000, 2).unscaledValue().toByteArray()),
new Fixed2(BigDecimal.valueOf(2000, 2).unscaledValue().toByteArray()));
}
@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
this.facesContext = facesContext;
Class<?> type = ValueExpressionHelper.getValueType(facesContext, uiComponent,
Lists.<Class<?>> newArrayList(DateTime.class, LocalDate.class, LocalTime.class));
Preconditions.checkArgument(type != null, "DateTimeConverter is not attached to a component bound to either a"
+ " DateTime, LocalDate, or LocalTime.");
if (value instanceof LocalDate) {
LocalDate localDate = (LocalDate) value;
return getAsStringValue(facesContext, uiComponent, localDate.toDateTimeAtStartOfDay(getTimeZone()));
}
if (value instanceof LocalTime) {
LocalTime localTime = (LocalTime) value;
return getAsStringValue(facesContext, uiComponent, localTime.toDateTimeToday(getTimeZone()));
}
if (value instanceof ReadablePartial) {
ReadablePartial readablePartial = (ReadablePartial) value;
return getAsStringValue(facesContext, uiComponent, readablePartial.toDateTime(new DateTime()));
}
this.facesContext = null;
return getAsStringValue(facesContext, uiComponent, value);
}
@Override
public void run() {
removeCallbacks(this);
mPrayTimes.setCoordinates(mLat, mLng, mAlt);
mQiblaTime = mPrayTimes.getQiblaTime();
LocalTime sunrise = LocalTime.parse(mPrayTimes.getTime(Times.Sunrise));
LocalTime sunset = LocalTime.parse(mPrayTimes.getTime(Times.Sunset));
LocalTime current = LocalTime.now();
mShowSun = !(sunset.isBefore(current) || sunrise.isAfter(current));
mSunriseAngle = Math.toDegrees(getAzimuth(sunrise.toDateTimeToday().getMillis(), mLat, mLng)) - mQiblaAngle - 90;
mSunsetAngle = Math.toDegrees(getAzimuth(sunset.toDateTimeToday().getMillis(), mLat, mLng)) - mQiblaAngle - 90;
mCurrentAngle = Math.toDegrees(getAzimuth(current.toDateTimeToday().getMillis(), mLat, mLng)) - mQiblaAngle - 90;
while (mSunriseAngle < 0) mSunriseAngle += 360;
while (mSunsetAngle < 0) mSunsetAngle += 360;
while (mSunriseAngle >= 360) mSunriseAngle -= 360;
while (mSunsetAngle >= 360) mSunsetAngle -= 360;
if (mSunsetAngle > mSunriseAngle) mSunsetAngle -= 360;
invalidate();
}
private TherapeuticLinkType mapTherapeuticLinkType(TherapeuticLink link) throws TherLinkBusinessConnectorException {
TherapeuticLinkType therLink = new TherapeuticLinkType();
therLink.setCd(this.mapCdTherapeuticLink(link.getType()));
therLink.setComment(link.getComment());
if (link.getEndDate() != null) {
therLink.setEnddate(link.getEndDate().toDateTime(LocalTime.MIDNIGHT));
}
if (link.getStartDate() != null) {
therLink.setStartdate(link.getStartDate().toDateTime(LocalTime.MIDNIGHT));
}
HcParty hcParty = link.getHcParty();
therLink.getHcparties().add(HcPartyMapper.mapHcPartyIdType(hcParty));
therLink.setPatient(this.mapPatient(link.getPatient()));
return therLink;
}
private TherapeuticLinkType mapTherapeuticLinkType(TherapeuticLink link) throws TherLinkBusinessConnectorException {
TherapeuticLinkType therLink = new TherapeuticLinkType();
therLink.setCd(this.mapCdTherapeuticLink(link.getType()));
therLink.setComment(link.getComment());
if (link.getEndDate() != null) {
therLink.setEnddate(link.getEndDate().toDateTime(LocalTime.MIDNIGHT));
}
if (link.getStartDate() != null) {
therLink.setStartdate(link.getStartDate().toDateTime(LocalTime.MIDNIGHT));
}
HcParty hcParty = link.getHcParty();
therLink.getHcparties().add(HcPartyMapper.mapHcPartyIdType(hcParty));
therLink.setPatient(this.mapPatient(link.getPatient()));
return therLink;
}
/**
* Tests that deserialising a null string returns null
*/
@Test
public void testDeserialiseNullString()
{
final Gson gson = Converters.registerLocalTime(new GsonBuilder()).create();
assertThat(gson.fromJson((String) null, LocalTime.class), is(nullValue()));
}
@Test
public void canHandle() throws Exception {
assertTrue(converter.canHandle("2017-09-03", TypeToken.of(LocalTime.class)));
assertTrue(converter.canHandle("2017-09-03", TypeToken.of(LocalDate.class)));
assertTrue(converter.canHandle("2017-09-03", TypeToken.of(LocalDateTime.class)));
assertFalse(converter.canHandle("2017-09-03", TypeToken.of(Duration.class)));
assertFalse(converter.canHandle(new Date(), TypeToken.of(LocalDate.class)));
}
@Override
public void setObject(Object value) {
if (value == null) {
setNull();
} else if (value instanceof Integer) {
setInt((Integer) value);
} else if (value instanceof Long) {
setLong((Long) value);
} else if (value instanceof String) {
setString((String) value);
} else if (value instanceof Double) {
setDouble((Double) value);
} else if (value instanceof Float) {
setDouble((Float) value);
} else if (value instanceof BigDecimal) {
setDecimal((BigDecimal) value);
} else if (value instanceof Period) {
setPeriod((Period) value);
} else if (value instanceof LocalTime) {
setTime((LocalTime) value);
} else if (value instanceof LocalDate) {
setDate((LocalDate) value);
} else if (value instanceof Instant) {
setTimestamp((Instant) value);
} else if (value instanceof byte[]) {
final byte[] bytes = (byte[]) value;
setBytes(bytes, bytes.length);
} else if (value instanceof Byte) {
setInt((Byte) value);
} else if (value instanceof Short) {
setInt((Short) value);
} else if (value instanceof Boolean) {
setBoolean((boolean) value);
} else {
throw conversionError(value.getClass().getSimpleName());
}
}
@Override
public void setTime(final LocalTime value) {
if (value == null) {
baseWriter.setNull();
} else {
try {
baseWriter.setString(dateTimeFormatter.print(value));
}
catch (final IllegalStateException e) {
throw InvalidConversionError.writeError(schema(), value, e);
}
}
}
private static Object optimize(@Language("SQL") String expression)
{
assertRoundTrip(expression);
Expression parsedExpression = planExpression(expression);
Map<NodeRef<Expression>, Type> expressionTypes = getTypes(TEST_SESSION, METADATA, SYMBOL_TYPES, parsedExpression);
ExpressionInterpreter interpreter = expressionOptimizer(parsedExpression, METADATA, TEST_SESSION, expressionTypes);
return interpreter.optimize(symbol -> {
switch (symbol.getName().toLowerCase(ENGLISH)) {
case "bound_integer":
return 1234L;
case "bound_long":
return 1234L;
case "bound_string":
return utf8Slice("hello");
case "bound_double":
return 12.34;
case "bound_date":
return new LocalDate(2001, 8, 22).toDateMidnight(DateTimeZone.UTC).getMillis();
case "bound_time":
return new LocalTime(3, 4, 5, 321).toDateTime(new DateTime(0, DateTimeZone.UTC)).getMillis();
case "bound_timestamp":
return new DateTime(2001, 8, 22, 3, 4, 5, 321, DateTimeZone.UTC).getMillis();
case "bound_pattern":
return utf8Slice("%el%");
case "bound_timestamp_with_timezone":
return SqlTimestampWithTimeZone.newInstance(3, new DateTime(1970, 1, 1, 1, 0, 0, 999, DateTimeZone.UTC).getMillis(), 0, getTimeZoneKey("Z"));
case "bound_varbinary":
return Slices.wrappedBuffer((byte) 0xab);
case "bound_decimal_short":
return 12345L;
case "bound_decimal_long":
return Decimals.encodeUnscaledValue(new BigInteger("12345678901234567890123"));
}
return symbol.toSymbolReference();
});
}
private LocalTime getTime() {
if (time == null) {
synchronized (this) {
if (time == null) {
time = LocalTime.fromMillisOfDay(millisOfDay);
}
}
}
return time;
}
@Test
public void testSpecificType() throws Exception {
JodaTimeRecord record = new JodaTimeRecord();
record.setTypeTimestampMillis(DateTime.parse("2010-06-30T01:20:20"));
record.setTypeDate(LocalDate.parse("2014-03-01"));
record.setTypeTimeMillis(LocalTime.parse("12:12:12"));
SpecificDatumWriter<JodaTimeRecord> datumWriter = new SpecificDatumWriter<>(JodaTimeRecord.class);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Encoder encoder = EncoderFactory.get().binaryEncoder(byteArrayOutputStream, null);
datumWriter.write(record, encoder);
encoder.flush();
byte[] input = byteArrayOutputStream.toByteArray();
DataType dataType = ROW(
FIELD("type_timestamp_millis", TIMESTAMP(3)),
FIELD("type_date", DATE()),
FIELD("type_time_millis", TIME(3)));
final RowType rowType = (RowType) dataType.getLogicalType();
final TypeInformation<RowData> typeInfo = new RowDataTypeInfo(rowType);
AvroRowDataSerializationSchema serializationSchema = new AvroRowDataSerializationSchema(rowType);
serializationSchema.open(null);
AvroRowDataDeserializationSchema deserializationSchema =
new AvroRowDataDeserializationSchema(rowType, typeInfo);
deserializationSchema.open(null);
RowData rowData = deserializationSchema.deserialize(input);
byte[] output = serializationSchema.serialize(rowData);
RowData rowData2 = deserializationSchema.deserialize(output);
Assert.assertEquals(rowData, rowData2);
Assert.assertEquals("2010-06-30T01:20:20", rowData.getTimestamp(0, 3).toString());
Assert.assertEquals("2014-03-01", DataFormatConverters.LocalDateConverter.INSTANCE.toExternal(
rowData.getInt(1)).toString());
Assert.assertEquals("12:12:12", DataFormatConverters.LocalTimeConverter.INSTANCE.toExternal(
rowData.getInt(2)).toString());
}
@Test
public void canHandle() throws Exception {
assertTrue(converter.canHandle(new Date(), TypeToken.of(LocalTime.class)));
assertTrue(converter.canHandle(new Date(), TypeToken.of(LocalDate.class)));
assertTrue(converter.canHandle(new Date(), TypeToken.of(LocalDateTime.class)));
assertFalse(converter.canHandle(new Date(), TypeToken.of(Duration.class)));
assertFalse(converter.canHandle("2017-09-03", TypeToken.of(LocalDate.class)));
}
@Override
public void write(Kryo kryo, Output output, LocalTime object) {
final int time = object.getMillisOfDay();
output.writeInt(time, true);
final Chronology chronology = object.getChronology();
if (chronology != null && chronology != ISOChronology.getInstanceUTC()) {
throw new RuntimeException("Unsupported chronology: " + chronology);
}
}
private void output(final AvroOutputFormat<User> outputFormat) throws IOException {
outputFormat.configure(new Configuration());
outputFormat.open(1, 1);
for (int i = 0; i < 100; i++) {
User user = new User();
user.setName("testUser");
user.setFavoriteNumber(1);
user.setFavoriteColor("blue");
user.setTypeBoolTest(true);
user.setTypeArrayString(Collections.emptyList());
user.setTypeArrayBoolean(Collections.emptyList());
user.setTypeEnum(Colors.BLUE);
user.setTypeMap(Collections.emptyMap());
user.setTypeBytes(ByteBuffer.allocate(10));
user.setTypeDate(LocalDate.parse("2014-03-01"));
user.setTypeTimeMillis(LocalTime.parse("12:12:12"));
user.setTypeTimeMicros(123456);
user.setTypeTimestampMillis(DateTime.parse("2014-03-01T12:12:12.321Z"));
user.setTypeTimestampMicros(123456L);
// 20.00
user.setTypeDecimalBytes(ByteBuffer.wrap(BigDecimal.valueOf(2000, 2).unscaledValue().toByteArray()));
// 20.00
user.setTypeDecimalFixed(new Fixed2(BigDecimal.valueOf(2000, 2).unscaledValue().toByteArray()));
outputFormat.writeRecord(user);
}
outputFormat.close();
}
@Test
public void testGeneratedObjectWithNullableFields() {
List<CharSequence> strings = Arrays.asList(new CharSequence[] { "These", "strings", "should", "be", "recognizable", "as", "a", "meaningful", "sequence" });
List<Boolean> bools = Arrays.asList(true, true, false, false, true, false, true, true);
Map<CharSequence, Long> map = new HashMap<>();
map.put("1", 1L);
map.put("2", 2L);
map.put("3", 3L);
byte[] b = new byte[16];
new Random().nextBytes(b);
Fixed16 f = new Fixed16(b);
Address addr = new Address(239, "6th Main", "Bangalore", "Karnataka", "560075");
User user = new User(
"Freudenreich",
1337,
"macintosh gray",
1234567890L,
3.1415926,
null,
true,
strings,
bools,
null,
Colors.GREEN,
map,
f,
Boolean.TRUE,
addr,
ByteBuffer.wrap(b),
LocalDate.parse("2014-03-01"),
LocalTime.parse("12:12:12"),
123456,
DateTime.parse("2014-03-01T12:12:12.321Z"),
123456L,
ByteBuffer.wrap(BigDecimal.valueOf(2000, 2).unscaledValue().toByteArray()), // 20.00
new Fixed2(BigDecimal.valueOf(2000, 2).unscaledValue().toByteArray())); // 20.00
testObjectSerialization(user);
}
private Time convertToTime(Object object) {
final long millis;
if (object instanceof Integer) {
millis = (Integer) object;
} else {
// use 'provided' Joda time
final LocalTime value = (LocalTime) object;
millis = (long) value.get(DateTimeFieldType.millisOfDay());
}
return new Time(millis - LOCAL_TZ.getOffset(millis));
}
private void output(final AvroOutputFormat<User> outputFormat) throws IOException {
outputFormat.configure(new Configuration());
outputFormat.open(1, 1);
for (int i = 0; i < 100; i++) {
User user = new User();
user.setName("testUser");
user.setFavoriteNumber(1);
user.setFavoriteColor("blue");
user.setTypeBoolTest(true);
user.setTypeArrayString(Collections.emptyList());
user.setTypeArrayBoolean(Collections.emptyList());
user.setTypeEnum(Colors.BLUE);
user.setTypeMap(Collections.emptyMap());
user.setTypeBytes(ByteBuffer.allocate(10));
user.setTypeDate(LocalDate.parse("2014-03-01"));
user.setTypeTimeMillis(LocalTime.parse("12:12:12"));
user.setTypeTimeMicros(123456);
user.setTypeTimestampMillis(DateTime.parse("2014-03-01T12:12:12.321Z"));
user.setTypeTimestampMicros(123456L);
// 20.00
user.setTypeDecimalBytes(ByteBuffer.wrap(BigDecimal.valueOf(2000, 2).unscaledValue().toByteArray()));
// 20.00
user.setTypeDecimalFixed(new Fixed2(BigDecimal.valueOf(2000, 2).unscaledValue().toByteArray()));
outputFormat.writeRecord(user);
}
outputFormat.close();
}
@Test
public void testToChar() throws Exception {
String expectedResults[] = {(new LocalDate(2008, 2, 23)).toString("yyyy-MMM-dd"),
(new LocalTime(12, 20, 30)).toString("HH mm ss"),
(new LocalDateTime(2008, 2, 23, 12, 0, 0)).toString("yyyy MMM dd HH:mm:ss")};
testCommon(expectedResults, "/functions/date/to_char.json", "/test_simple_date.json");
}
public void testParseLocalTime_simple() {
assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30Z"));
assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30+18:00"));
assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30-18:00"));
assertEquals(new LocalTime(10, 20, 30, 0, BUDDHIST_PARIS),
g.withChronology(BUDDHIST_PARIS).parseLocalTime("2004-06-09T10:20:30Z"));
try {
g.parseDateTime("ABC");
fail();
} catch (IllegalArgumentException ex) {}
}
public void testParseLocalTime_simple() {
assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30Z"));
assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30+18:00"));
assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30-18:00"));
assertEquals(new LocalTime(10, 20, 30, 0, BUDDHIST_PARIS),
g.withChronology(BUDDHIST_PARIS).parseLocalTime("2004-06-09T10:20:30Z"));
try {
g.parseDateTime("ABC");
fail();
} catch (IllegalArgumentException ex) {}
}
private GetTherapeuticLinkSelectType mapGetTherapeuticLinkSelectType(TherapeuticLink link) throws TherLinkBusinessConnectorException {
GetTherapeuticLinkSelectType request = new GetTherapeuticLinkSelectType();
if (link.getStartDate() != null) {
request.setBegindate(link.getStartDate().toDateTime(LocalTime.MIDNIGHT));
}
if (link.getEndDate() != null) {
request.setEnddate(link.getEndDate().toDateTime(LocalTime.MIDNIGHT));
}
if (link.getType() != null) {
CDTHERAPEUTICLINK therlinkType = this.createTherapeuticLinkType(link.getType());
request.getCds().add(therlinkType);
}
if (link.getStatus() != null) {
request.setTherapeuticlinkstatus(link.getStatus().toString().toLowerCase(Locale.getDefault()));
}
if (link.getPatient() != null) {
request.getPatientsAndHcparties().add(this.mapPatient(link.getPatient()));
}
if (link.getHcParty() != null) {
request.getPatientsAndHcparties().add(HcPartyMapper.mapHcPartyIdType(link.getHcParty()));
}
return request;
}
public GetTherapeuticLinkRequest createGetTherapeuticLinkRequest(TherapeuticLink query, int maxRowsToUse, Proof... prooves) throws TechnicalConnectorException, TherLinkBusinessConnectorException, InstantiationException {
if (query == null) {
TherLinkBusinessConnectorException therLinkBusinessConnectorException = new TherLinkBusinessConnectorException(TherLinkBusinessConnectorExceptionValues.REQUIRED_FIELD_NULL, new Object[]{"query is required to create a GetTherapeuticLinkRequest"});
LOGGER.error(therLinkBusinessConnectorException.getMessage());
throw therLinkBusinessConnectorException;
} else {
CommonObjectBuilder commonBuilder = RequestObjectBuilderFactory.getCommonBuilder();
DateTime date = query.getStartDate() == null ? null : query.getStartDate().toDateTime(LocalTime.MIDNIGHT);
Author createAuthor = commonBuilder.createAuthor(this.getAuthorHcParties());
GetTherapeuticLinkRequest request = new GetTherapeuticLinkRequest(date, commonBuilder.createKmehrID(), createAuthor, query, maxRowsToUse, prooves);
this.validateMaxRowsValue(request);
return request;
}
}
@Override
public void setTime(LocalTime value) { }
@Override
public void setTime(LocalTime value) {
baseWriter.setTime(value);
}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
@Override
public LocalTime convert(CharSequence in, Context context) throws Exception {
if (in == null || in.length() == 0) return null;
return dateTimeFormatter.parseLocalTime(String.valueOf(in));
}
@Test
public void testConvertNull() {
LocalTimeConverter localTimeConverter = new LocalTimeConverter();
LocalTime convert = localTimeConverter.convert(null);
assertNotNull(convert);
}