下面列出了怎么用org.joda.time.ReadableInstant的API类实例代码及写法,或者点击链接到github查看源代码。
private String getAsStringValue(FacesContext facesContext, UIComponent uiComponent, Object value) {
if (facesContext == null) {
throw new NullPointerException("facesContext");
}
if (uiComponent == null) {
throw new NullPointerException("uiComponent");
}
if (value == null) {
return "";
}
if (value instanceof String) {
return (String) value;
}
DateTimeFormatter format = getDateFormat(uiComponent);
try {
return format.print((ReadableInstant) value);
}
catch (Exception e) {
throw new ConverterException("Cannot convert value '" + value + "'");
}
}
private void populateRegistrationStates(final ReadableInstant beginDateTime, final ReadableInstant endDateTime,
final Collection<RegistrationState> result) {
List<RegistrationState> sortedRegistrationsStates = new ArrayList<RegistrationState>(getRegistrationStatesSet());
Collections.sort(sortedRegistrationsStates, RegistrationState.DATE_COMPARATOR);
for (ListIterator<RegistrationState> iter = sortedRegistrationsStates.listIterator(sortedRegistrationsStates.size()); iter
.hasPrevious();) {
RegistrationState state = iter.previous();
if (state.getStateDate().isAfter(endDateTime)) {
continue;
}
result.add(state);
if (!state.getStateDate().isAfter(beginDateTime)) {
break;
}
}
}
public void testBigHashtable() {
Converter[] array = new Converter[] {
c1, c2, c3, c4,
};
ConverterSet set = new ConverterSet(array);
set.select(Boolean.class);
set.select(Character.class);
set.select(Byte.class);
set.select(Short.class);
set.select(Integer.class);
set.select(Long.class);
set.select(Float.class);
set.select(Double.class);
set.select(null);
set.select(Calendar.class);
set.select(GregorianCalendar.class);
set.select(DateTime.class);
set.select(DateMidnight.class);
set.select(ReadableInstant.class);
set.select(ReadableDateTime.class);
set.select(ReadWritableInstant.class); // 16
set.select(ReadWritableDateTime.class);
set.select(DateTime.class);
assertEquals(4, set.size());
}
public void testGetInstantConverter() {
InstantConverter c = ConverterManager.getInstance().getInstantConverter(new Long(0L));
assertEquals(Long.class, c.getSupportedType());
c = ConverterManager.getInstance().getInstantConverter(new DateTime());
assertEquals(ReadableInstant.class, c.getSupportedType());
c = ConverterManager.getInstance().getInstantConverter("");
assertEquals(String.class, c.getSupportedType());
c = ConverterManager.getInstance().getInstantConverter(new Date());
assertEquals(Date.class, c.getSupportedType());
c = ConverterManager.getInstance().getInstantConverter(new GregorianCalendar());
assertEquals(Calendar.class, c.getSupportedType());
c = ConverterManager.getInstance().getInstantConverter(null);
assertEquals(null, c.getSupportedType());
try {
ConverterManager.getInstance().getInstantConverter(Boolean.TRUE);
fail();
} catch (IllegalArgumentException ex) {}
}
/**
* Compares this object with the specified object for ascending
* millisecond instant order. This ordering is inconsistent with
* equals, as it ignores the Chronology.
* <p>
* All ReadableInstant instances are accepted.
*
* @param other a readable instant to check against
* @return negative value if this is less, 0 if equal, or positive value if greater
* @throws NullPointerException if the object is null
* @throws ClassCastException if the object type is not supported
*/
public int compareTo(ReadableInstant other) {
if (this == other) {
return 0;
}
long otherMillis = other.getMillis();
long thisMillis = getMillis();
// cannot do (thisMillis - otherMillis) as can overflow
if (thisMillis == otherMillis) {
return 0;
}
if (thisMillis < otherMillis) {
return -1;
} else {
return 1;
}
}
/**
* Creates a period from the given interval endpoints.
*
* @param startInstant interval start, null means now
* @param endInstant interval end, null means now
* @param type which set of fields this period supports, null means standard
* @throws IllegalArgumentException if period type is invalid
*/
protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) {
super();
type = checkPeriodType(type);
if (startInstant == null && endInstant == null) {
iType = type;
iValues = new int[size()];
} else {
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
}
@Override
public Printer<?> getPrinter(DateTimeFormat annotation, Class<?> fieldType) {
DateTimeFormatter formatter = getFormatter(annotation, fieldType);
if (ReadablePartial.class.isAssignableFrom(fieldType)) {
return new ReadablePartialPrinter(formatter);
}
else if (ReadableInstant.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) {
// assumes Calendar->ReadableInstant converter is registered
return new ReadableInstantPrinter(formatter);
}
else {
// assumes Date->Long converter is registered
return new MillisecondInstantPrinter(formatter);
}
}
/**
* Compare this field to the same field on another instant.
* <p>
* The comparison is based on the value of the same field type, irrespective
* of any difference in chronology. Thus, if this property represents the
* hourOfDay field, then the hourOfDay field of the other instant will be queried
* whether in the same chronology or not.
*
* @param instant the instant to compare to
* @return negative value if this is less, 0 if equal, or positive value if greater
* @throws IllegalArgumentException if the instant is null or the instant
* doesn't support the field of this property
*/
public int compareTo(ReadableInstant instant) {
if (instant == null) {
throw new IllegalArgumentException("The instant must not be null");
}
int thisValue = get();
int otherValue = instant.get(getFieldType());
if (thisValue < otherValue) {
return -1;
} else if (thisValue > otherValue) {
return 1;
} else {
return 0;
}
}
@Override
public Printer<?> getPrinter(DateTimeFormat annotation, Class<?> fieldType) {
DateTimeFormatter formatter = getFormatter(annotation, fieldType);
if (ReadablePartial.class.isAssignableFrom(fieldType)) {
return new ReadablePartialPrinter(formatter);
}
else if (ReadableInstant.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) {
// assumes Calendar->ReadableInstant converter is registered
return new ReadableInstantPrinter(formatter);
}
else {
// assumes Date->Long converter is registered
return new MillisecondInstantPrinter(formatter);
}
}
/**
* Creates a duration from the given interval endpoints.
*
* @param start interval start, null means now
* @param end interval end, null means now
* @throws ArithmeticException if the duration exceeds a 64-bit long
*/
protected BaseDuration(ReadableInstant start, ReadableInstant end) {
super();
if (start == end) {
iMillis = 0L;
} else {
long startMillis = DateTimeUtils.getInstantMillis(start);
long endMillis = DateTimeUtils.getInstantMillis(end);
iMillis = FieldUtils.safeAdd(endMillis, -startMillis);
}
}
/**
* Constructs an interval from a start and end instant.
*
* @param start start of this interval, null means now
* @param end end of this interval, null means now
* @throws IllegalArgumentException if the end is before the start
*/
protected BaseInterval(ReadableInstant start, ReadableInstant end) {
super();
if (start == null && end == null) {
iStartMillis = iEndMillis = DateTimeUtils.currentTimeMillis();
iChronology = ISOChronology.getInstance();
} else {
iChronology = DateTimeUtils.getInstantChronology(start);
iStartMillis = DateTimeUtils.getInstantMillis(start);
iEndMillis = DateTimeUtils.getInstantMillis(end);
checkInterval(iStartMillis, iEndMillis);
}
}
/**
* Method serializes a primitive to a String. Most types are serialized with the standard toString method.
* Bytes and byte arrays pass through as they are whilst DATETIME types gets converted to a ISO8601 formatted String.
* @param type the {@link Row row} field type
* @param value the value from the {@link Row row}
* @return a ByteString.
*/
protected static String primitiveFieldToString(TypeName type, Object value) {
if (value == null) {
return "";
}
String string;
switch (type) {
case BYTE:
return BaseEncoding.base64().encode(new byte[] {(byte) value});
case INT16:
case DECIMAL:
case INT64:
case INT32:
case FLOAT:
case DOUBLE:
case STRING:
case BOOLEAN:
return value.toString();
case DATETIME:
ReadableInstant dateTime = ((ReadableInstant) value);
// Write a ISO8601 formatted String.
return dateTime.toString();
case BYTES:
return BaseEncoding.base64().encode((byte[]) value);
default:
throw new UnsupportedOperationException(
"Unsupported type: " + type + " This method only supports primitives.");
}
}
/**
* Creates a period from the given duration and end point.
*
* @param duration the duration of the interval, null means zero-length
* @param endInstant the interval end, null means now
* @param type which set of fields this period supports, null means standard
*/
protected BasePeriod(ReadableDuration duration, ReadableInstant endInstant, PeriodType type) {
super();
type = checkPeriodType(type);
long durationMillis = DateTimeUtils.getDurationMillis(duration);
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
long startMillis = FieldUtils.safeSubtract(endMillis, durationMillis);
Chronology chrono = DateTimeUtils.getInstantChronology(endInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
/**
* Creates a period from the given start point and duration.
*
* @param startInstant the interval start, null means now
* @param duration the duration of the interval, null means zero-length
* @param type which set of fields this period supports, null means standard
*/
protected BasePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) {
super();
type = checkPeriodType(type);
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
long durationMillis = DateTimeUtils.getDurationMillis(duration);
long endMillis = FieldUtils.safeAdd(startMillis, durationMillis);
Chronology chrono = DateTimeUtils.getInstantChronology(startInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
/**
* Constructs an interval from a start instant and a time period.
* <p>
* When forming the interval, the chronology from the instant is used
* if present, otherwise the chronology of the period is used.
*
* @param start start of this interval, null means now
* @param period the period of this interval, null means zero length
* @throws IllegalArgumentException if the end is before the start
* @throws ArithmeticException if the end instant exceeds the capacity of a long
*/
protected BaseInterval(ReadableInstant start, ReadablePeriod period) {
super();
Chronology chrono = DateTimeUtils.getInstantChronology(start);
iChronology = chrono;
iStartMillis = DateTimeUtils.getInstantMillis(start);
if (period == null) {
iEndMillis = iStartMillis;
} else {
iEndMillis = chrono.add(period, iStartMillis, 1);
}
checkInterval(iStartMillis, iEndMillis);
}
@Override
public String convert(ReadableInstant source) {
if (source == null) {
return null;
}
return (ClientUtils.escapeQueryChars(FORMATTER.print(source.getMillis())));
}
/**
* Constructs an interval from a millisecond duration and an end instant.
*
* @param duration the duration of this interval, null means zero length
* @param end end of this interval, null means now
* @throws IllegalArgumentException if the end is before the start
* @throws ArithmeticException if the start instant exceeds the capacity of a long
*/
protected BaseInterval(ReadableDuration duration, ReadableInstant end) {
super();
iChronology = DateTimeUtils.getInstantChronology(end);
iEndMillis = DateTimeUtils.getInstantMillis(end);
long durationMillis = DateTimeUtils.getDurationMillis(duration);
iStartMillis = FieldUtils.safeAdd(iEndMillis, -durationMillis);
checkInterval(iStartMillis, iEndMillis);
}
/**
* Compare this field to the same field on another instant.
* <p>
* The comparison is based on the value of the same field type, irrespective
* of any difference in chronology. Thus, if this property represents the
* hourOfDay field, then the hourOfDay field of the other instant will be queried
* whether in the same chronology or not.
*
* @param instant the instant to compare to
* @return negative value if this is less, 0 if equal, or positive value if greater
* @throws IllegalArgumentException if the instant is null or the instant
* doesn't support the field of this property
*/
public int compareTo(ReadableInstant instant) {
if (instant == null) {
throw new IllegalArgumentException("The instant must not be null");
}
int thisValue = get();
int otherValue = instant.get(getFieldType());
if (thisValue < otherValue) {
return -1;
} else if (thisValue > otherValue) {
return 1;
} else {
return 0;
}
}
@Override
public void encode(InputT value, OutputStream outStream) throws CoderException, IOException {
BaseT baseType = logicalType.toBaseType(value);
if (isDateTime) {
baseType = (BaseT) ((ReadableInstant) baseType).toInstant();
}
baseTypeCoder.encode(baseType, outStream);
}
/**
* Creates a period from the given duration and end point.
*
* @param duration the duration of the interval, null means zero-length
* @param endInstant the interval end, null means now
* @param type which set of fields this period supports, null means standard
*/
protected BasePeriod(ReadableDuration duration, ReadableInstant endInstant, PeriodType type) {
super();
type = checkPeriodType(type);
long durationMillis = DateTimeUtils.getDurationMillis(duration);
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
long startMillis = FieldUtils.safeSubtract(endMillis, durationMillis);
Chronology chrono = DateTimeUtils.getInstantChronology(endInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
/** Converts a {@link ReadableInstant} into a Dateflow API time value. */
public static String toCloudTime(ReadableInstant instant) {
// Note that since Joda objects use millisecond resolution, we always
// produce either no fractional seconds or fractional seconds with
// millisecond resolution.
// Translate the ReadableInstant to a DateTime with ISOChronology.
DateTime time = new DateTime(instant);
int millis = time.getMillisOfSecond();
if (millis == 0) {
return String.format(
"%04d-%02d-%02dT%02d:%02d:%02dZ",
time.getYear(),
time.getMonthOfYear(),
time.getDayOfMonth(),
time.getHourOfDay(),
time.getMinuteOfHour(),
time.getSecondOfMinute());
} else {
return String.format(
"%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
time.getYear(),
time.getMonthOfYear(),
time.getDayOfMonth(),
time.getHourOfDay(),
time.getMinuteOfHour(),
time.getSecondOfMinute(),
millis);
}
}
/**
* Gets the chronology, which is taken from the ReadableInstant.
* If the chronology on the instant is null, the ISOChronology in the
* specified time zone is used.
* If the chronology on the instant is not in the specified zone, it is
* adapted.
*
* @param object the ReadableInstant to convert, must not be null
* @param zone the specified zone to use, null means default zone
* @return the chronology, never null
*/
public Chronology getChronology(Object object, DateTimeZone zone) {
Chronology chrono = ((ReadableInstant) object).getChronology();
if (chrono == null) {
return ISOChronology.getInstance(zone);
}
DateTimeZone chronoZone = chrono.getZone();
if (chronoZone != zone) {
chrono = chrono.withZone(zone);
if (chrono == null) {
return ISOChronology.getInstance(zone);
}
}
return chrono;
}
public XmlXContentBuilder value(ReadableInstant date, DateTimeFormatter dateTimeFormatter) throws IOException {
if (date == null) {
return nullValue();
}
return value(dateTimeFormatter.print(date));
}
public XmlXContentBuilder field(String name, ReadableInstant date, DateTimeFormatter formatter) throws IOException {
field(name);
return value(date, formatter);
}
private static Hours hoursBetween(ReadableInstant start, ReadableInstant end)
{
return Hours.hoursBetween(start, end);
}
@Override
public void registerFormatters(FormatterRegistry registry) {
JodaTimeConverters.registerConverters(registry);
DateTimeFormatter dateFormatter = getFormatter(Type.DATE);
DateTimeFormatter timeFormatter = getFormatter(Type.TIME);
DateTimeFormatter dateTimeFormatter = getFormatter(Type.DATE_TIME);
addFormatterForFields(registry,
new ReadablePartialPrinter(dateFormatter),
new LocalDateParser(dateFormatter),
LocalDate.class);
addFormatterForFields(registry,
new ReadablePartialPrinter(timeFormatter),
new LocalTimeParser(timeFormatter),
LocalTime.class);
addFormatterForFields(registry,
new ReadablePartialPrinter(dateTimeFormatter),
new LocalDateTimeParser(dateTimeFormatter),
LocalDateTime.class);
addFormatterForFields(registry,
new ReadableInstantPrinter(dateTimeFormatter),
new DateTimeParser(dateTimeFormatter),
ReadableInstant.class);
// In order to retain backwards compatibility we only register Date/Calendar
// types when a user defined formatter is specified (see SPR-10105)
if (this.formatters.containsKey(Type.DATE_TIME)) {
addFormatterForFields(registry,
new ReadableInstantPrinter(dateTimeFormatter),
new DateTimeParser(dateTimeFormatter),
Date.class, Calendar.class);
}
registry.addFormatterForFieldType(Period.class, new PeriodFormatter());
registry.addFormatterForFieldType(Duration.class, new DurationFormatter());
registry.addFormatterForFieldType(YearMonth.class, new YearMonthFormatter());
registry.addFormatterForFieldType(MonthDay.class, new MonthDayFormatter());
registry.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory());
}
private static long toMillis(ReadableInstant time) {
DateTime dateTime = time instanceof DateTime ? (DateTime) time : new DateTime(time);
DateTime utcDateTime = dateTime.withZoneRetainFields(DateTimeZone.UTC);
return utcDateTime.getMillis();
}
@Override
public void registerFormatters(FormatterRegistry registry) {
JodaTimeConverters.registerConverters(registry);
DateTimeFormatter dateFormatter = getFormatter(Type.DATE);
DateTimeFormatter timeFormatter = getFormatter(Type.TIME);
DateTimeFormatter dateTimeFormatter = getFormatter(Type.DATE_TIME);
addFormatterForFields(registry,
new ReadablePartialPrinter(dateFormatter),
new LocalDateParser(dateFormatter),
LocalDate.class);
addFormatterForFields(registry,
new ReadablePartialPrinter(timeFormatter),
new LocalTimeParser(timeFormatter),
LocalTime.class);
addFormatterForFields(registry,
new ReadablePartialPrinter(dateTimeFormatter),
new LocalDateTimeParser(dateTimeFormatter),
LocalDateTime.class);
addFormatterForFields(registry,
new ReadableInstantPrinter(dateTimeFormatter),
new DateTimeParser(dateTimeFormatter),
ReadableInstant.class);
// In order to retain backwards compatibility we only register Date/Calendar
// types when a user defined formatter is specified (see SPR-10105)
if (this.formatters.containsKey(Type.DATE_TIME)) {
addFormatterForFields(registry,
new ReadableInstantPrinter(dateTimeFormatter),
new DateTimeParser(dateTimeFormatter),
Date.class, Calendar.class);
}
registry.addFormatterForFieldType(Period.class, new PeriodFormatter());
registry.addFormatterForFieldType(Duration.class, new DurationFormatter());
registry.addFormatterForFieldType(YearMonth.class, new YearMonthFormatter());
registry.addFormatterForFieldType(MonthDay.class, new MonthDayFormatter());
registry.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory());
}
@Override
public String print(ReadableInstant instant, Locale locale) {
return JodaTimeContextHolder.getFormatter(this.formatter, locale).print(instant);
}
@Override
public ReadableInstant convert(Date source) {
return new DateTime(source);
}