下面列出了怎么用org.joda.time.ReadWritablePeriod的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public int parseInto(ReadWritablePeriod period, String text, int position, Locale locale)
{
int bestValidPos = position;
ReadWritablePeriod bestValidPeriod = null;
int bestInvalidPos = position;
for (PeriodParser parser : parsers) {
ReadWritablePeriod parsedPeriod = new MutablePeriod();
int parsePos = parser.parseInto(parsedPeriod, text, position, locale);
if (parsePos >= position) {
if (parsePos > bestValidPos) {
bestValidPos = parsePos;
bestValidPeriod = parsedPeriod;
if (parsePos >= text.length()) {
break;
}
}
}
else if (parsePos < 0) {
parsePos = ~parsePos;
if (parsePos > bestInvalidPos) {
bestInvalidPos = parsePos;
}
}
}
if (bestValidPos > position || (bestValidPos == position)) {
// Restore the state to the best valid parse.
if (bestValidPeriod != null) {
period.setPeriod(bestValidPeriod);
}
return bestValidPos;
}
return ~bestInvalidPos;
}
/**
* Convert an ISO8601 duration to a Period.
* @param duration
* @return
* @throws WarpScriptException
*/
public static ReadWritablePeriodWithSubSecondOffset durationToPeriod(String duration) throws WarpScriptException {
// Separate seconds from digits below second precision
String[] tokens = UnsafeString.split(duration, '.');
long offset = 0;
if (tokens.length > 2) {
throw new WarpScriptException("Invalid ISO8601 duration");
}
if (2 == tokens.length) {
duration = tokens[0].concat("S");
String tmp = tokens[1].substring(0, tokens[1].length() - 1);
try {
offset = ((Double) (Double.parseDouble("0." + tmp) * Constants.TIME_UNITS_PER_S)).longValue();
} catch (NumberFormatException e) {
throw new WarpScriptException("Parsing of sub second precision part of duration has failed. tried to parse: " + tmp);
}
}
ReadWritablePeriod period = new MutablePeriod();
if (ISOPeriodFormat.standard().getParser().parseInto(period, duration, 0, Locale.US) < 0) {
throw new WarpScriptException("Parsing of duration without sub second precision has failed. Tried to parse: " + duration);
}
return new ReadWritablePeriodWithSubSecondOffset(period, offset);
}
/**
* Add a duration in ISO8601 duration format to a timestamp
* @param instant a timestamp since Unix Epoch
* @param periodAndOffset a period (with subsecond precision) to add
* @param dtz timezone
* @param N number of times the period is added
* @return resulting timestamp
*/
public static long addPeriod(long instant, ReadWritablePeriodWithSubSecondOffset periodAndOffset, DateTimeZone dtz, long N) {
ReadWritablePeriod period = periodAndOffset.getPeriod();
long offset = periodAndOffset.getOffset();
//
// Do the computation
//
DateTime dt = new DateTime(instant / Constants.TIME_UNITS_PER_MS, dtz);
//
// Add the duration
// Note that for performance reasons we add N times ISO8601 duration, then N times the sub seconds offset.
// This calculation is not exact in some rare edge cases e.g. in the last second of the 28th february on a year before a leap year if we add 'P1YT0.999999S'.
//
long M = N;
while (M > Integer.MAX_VALUE) {
dt = dt.withPeriodAdded(period, Integer.MAX_VALUE);
M = M - Integer.MAX_VALUE;
}
while (M < Integer.MIN_VALUE) {
dt = dt.withPeriodAdded(period, Integer.MIN_VALUE);
M = M - Integer.MIN_VALUE;
}
dt = dt.withPeriodAdded(period, Math.toIntExact(M));
// check if offset should be positive of negative
if (period.toPeriod().getSeconds() < 0) {
offset = -offset;
}
long ts = dt.getMillis() * Constants.TIME_UNITS_PER_MS;
ts += instant % Constants.TIME_UNITS_PER_MS;
ts += offset * N;
return ts;
}
void setFieldValue(ReadWritablePeriod period, int field, int value) {
switch (field) {
default:
break;
case YEARS:
period.setYears(value);
break;
case MONTHS:
period.setMonths(value);
break;
case WEEKS:
period.setWeeks(value);
break;
case DAYS:
period.setDays(value);
break;
case HOURS:
period.setHours(value);
break;
case MINUTES:
period.setMinutes(value);
break;
case SECONDS:
period.setSeconds(value);
break;
case MILLIS:
period.setMillis(value);
break;
}
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
if (periodStr.regionMatches(true, position, iText, 0, iText.length())) {
return position + iText.length();
}
return ~position;
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
PeriodParser[] parsers = iParsers;
if (parsers == null) {
throw new UnsupportedOperationException();
}
int len = parsers.length;
for (int i=0; i<len && position >= 0; i++) {
position = parsers[i].parseInto(period, periodStr, position, locale);
}
return position;
}
void setFieldValue(ReadWritablePeriod period, int field, int value) {
switch (field) {
default:
break;
case YEARS:
period.setYears(value);
break;
case MONTHS:
period.setMonths(value);
break;
case WEEKS:
period.setWeeks(value);
break;
case DAYS:
period.setDays(value);
break;
case HOURS:
period.setHours(value);
break;
case MINUTES:
period.setMinutes(value);
break;
case SECONDS:
period.setSeconds(value);
break;
case MILLIS:
period.setMillis(value);
break;
}
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
if (periodStr.regionMatches(true, position, iText, 0, iText.length())) {
return position + iText.length();
}
return ~position;
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
PeriodParser[] parsers = iParsers;
if (parsers == null) {
throw new UnsupportedOperationException();
}
int len = parsers.length;
for (int i=0; i<len && position >= 0; i++) {
position = parsers[i].parseInto(period, periodStr, position, locale);
}
return position;
}
void setFieldValue(ReadWritablePeriod period, int field, int value) {
switch (field) {
default:
break;
case YEARS:
period.setYears(value);
break;
case MONTHS:
period.setMonths(value);
break;
case WEEKS:
period.setWeeks(value);
break;
case DAYS:
period.setDays(value);
break;
case HOURS:
period.setHours(value);
break;
case MINUTES:
period.setMinutes(value);
break;
case SECONDS:
period.setSeconds(value);
break;
case MILLIS:
period.setMillis(value);
break;
}
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
if (periodStr.regionMatches(true, position, iText, 0, iText.length())) {
return position + iText.length();
}
return ~position;
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
PeriodParser[] parsers = iParsers;
if (parsers == null) {
throw new UnsupportedOperationException();
}
int len = parsers.length;
for (int i=0; i<len && position >= 0; i++) {
position = parsers[i].parseInto(period, periodStr, position, locale);
}
return position;
}
void setFieldValue(ReadWritablePeriod period, int field, int value) {
switch (field) {
default:
break;
case YEARS:
period.setYears(value);
break;
case MONTHS:
period.setMonths(value);
break;
case WEEKS:
period.setWeeks(value);
break;
case DAYS:
period.setDays(value);
break;
case HOURS:
period.setHours(value);
break;
case MINUTES:
period.setMinutes(value);
break;
case SECONDS:
period.setSeconds(value);
break;
case MILLIS:
period.setMillis(value);
break;
}
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
if (periodStr.regionMatches(true, position, iText, 0, iText.length())) {
return position + iText.length();
}
return ~position;
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
PeriodParser[] parsers = iParsers;
if (parsers == null) {
throw new UnsupportedOperationException();
}
int len = parsers.length;
for (int i=0; i<len && position >= 0; i++) {
position = parsers[i].parseInto(period, periodStr, position, locale);
}
return position;
}
/**
* Creates a new period based on another using the {@link ConverterManager}.
*
* @param period the period to convert
* @param type which set of fields this period supports, null means use type from object
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period is invalid
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
super();
PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
type = (type == null ? converter.getPeriodType(period) : type);
type = checkPeriodType(type);
iType = type;
if (this instanceof ReadWritablePeriod) {
iValues = new int[size()];
chrono = DateTimeUtils.getChronology(chrono);
converter.setInto((ReadWritablePeriod) this, period, chrono);
} else {
iValues = new MutablePeriod(period, type, chrono).getValues();
}
}
/**
* Creates a new period based on another using the {@link ConverterManager}.
*
* @param period the period to convert
* @param type which set of fields this period supports, null means use type from object
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period is invalid
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
super();
PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
type = (type == null ? converter.getPeriodType(period) : type);
type = checkPeriodType(type);
iType = type;
if (this instanceof ReadWritablePeriod) {
iValues = new int[size()];
chrono = DateTimeUtils.getChronology(chrono);
converter.setInto((ReadWritablePeriod) this, period, chrono);
} else {
iValues = new MutablePeriod(period, type, chrono).getValues();
}
}
@Override
public Object create(Object request, SpecimenContext context) {
if (!(request.equals(ReadablePeriod.class) || request.equals(ReadWritablePeriod.class)))
return new NoSpecimen();
DateTime dateA = (DateTime) context.resolve(DateTime.class);
DateTime dateB = (DateTime) context.resolve(DateTime.class);
if (dateA.isBefore(dateB))
return new MutablePeriod(dateA, dateB);
else
return new MutablePeriod(dateB, dateA);
}
/**
* Creates a new period based on another using the {@link ConverterManager}.
*
* @param period the period to convert
* @param type which set of fields this period supports, null means use type from object
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period is invalid
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
super();
PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
type = (type == null ? converter.getPeriodType(period) : type);
type = checkPeriodType(type);
iType = type;
if (this instanceof ReadWritablePeriod) {
iValues = new int[size()];
chrono = DateTimeUtils.getChronology(chrono);
converter.setInto((ReadWritablePeriod) this, period, chrono);
} else {
iValues = new MutablePeriod(period, type, chrono).getValues();
}
}
/**
* Sets the values of the mutable duration from the specified interval.
*
* @param writablePeriod the period to modify
* @param object the interval to set from
* @param chrono the chronology to use
*/
public void setInto(ReadWritablePeriod writablePeriod, Object object, Chronology chrono) {
ReadableInterval interval = (ReadableInterval) object;
chrono = (chrono != null ? chrono : DateTimeUtils.getIntervalChronology(interval));
long start = interval.getStartMillis();
long end = interval.getEndMillis();
int[] values = chrono.get(writablePeriod, start, end);
for (int i = 0; i < values.length; i++) {
writablePeriod.setValue(i, values[i]);
}
}
/**
* Extracts duration values from an object of this converter's type, and
* sets them into the given ReadWritableDuration.
*
* @param period period to get modified
* @param object the String to convert, must not be null
* @param chrono the chronology to use
* @return the millisecond duration
* @throws ClassCastException if the object is invalid
*/
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
String str = (String) object;
PeriodFormatter parser = ISOPeriodFormat.standard();
period.clear();
int pos = parser.parseInto(period, str, 0);
if (pos < str.length()) {
if (pos < 0) {
// Parse again to get a better exception thrown.
parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
}
throw new IllegalArgumentException("Invalid format: \"" + str + '"');
}
}
void setFieldValue(ReadWritablePeriod period, int field, int value) {
switch (field) {
default:
break;
case YEARS:
period.setYears(value);
break;
case MONTHS:
period.setMonths(value);
break;
case WEEKS:
period.setWeeks(value);
break;
case DAYS:
period.setDays(value);
break;
case HOURS:
period.setHours(value);
break;
case MINUTES:
period.setMinutes(value);
break;
case SECONDS:
period.setSeconds(value);
break;
case MILLIS:
period.setMillis(value);
break;
}
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
if (periodStr.regionMatches(true, position, iText, 0, iText.length())) {
return position + iText.length();
}
return ~position;
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
PeriodParser[] parsers = iParsers;
if (parsers == null) {
throw new UnsupportedOperationException();
}
int len = parsers.length;
for (int i=0; i<len && position >= 0; i++) {
position = parsers[i].parseInto(period, periodStr, position, locale);
}
return position;
}
/**
* Creates a new period based on another using the {@link ConverterManager}.
*
* @param period the period to convert
* @param type which set of fields this period supports, null means use type from object
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period is invalid
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
super();
PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
type = (type == null ? converter.getPeriodType(period) : type);
type = checkPeriodType(type);
iType = type;
if (this instanceof ReadWritablePeriod) {
iValues = new int[size()];
chrono = DateTimeUtils.getChronology(chrono);
converter.setInto((ReadWritablePeriod) this, period, chrono);
} else {
iValues = new MutablePeriod(period, type, chrono).getValues();
}
}
/**
* Sets the values of the mutable duration from the specified interval.
*
* @param writablePeriod the period to modify
* @param object the interval to set from
* @param chrono the chronology to use
*/
public void setInto(ReadWritablePeriod writablePeriod, Object object, Chronology chrono) {
ReadableInterval interval = (ReadableInterval) object;
chrono = (chrono != null ? chrono : DateTimeUtils.getIntervalChronology(interval));
long start = interval.getStartMillis();
long end = interval.getEndMillis();
int[] values = chrono.get(writablePeriod, start, end);
for (int i = 0; i < values.length; i++) {
writablePeriod.setValue(i, values[i]);
}
}
/**
* Extracts duration values from an object of this converter's type, and
* sets them into the given ReadWritableDuration.
*
* @param period period to get modified
* @param object the String to convert, must not be null
* @param chrono the chronology to use
* @return the millisecond duration
* @throws ClassCastException if the object is invalid
*/
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
String str = (String) object;
PeriodFormatter parser = ISOPeriodFormat.standard();
period.clear();
int pos = parser.parseInto(period, str, 0);
if (pos < str.length()) {
if (pos < 0) {
// Parse again to get a better exception thrown.
parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
}
throw new IllegalArgumentException("Invalid format: \"" + str + '"');
}
}
void setFieldValue(ReadWritablePeriod period, int field, int value) {
switch (field) {
default:
break;
case YEARS:
period.setYears(value);
break;
case MONTHS:
period.setMonths(value);
break;
case WEEKS:
period.setWeeks(value);
break;
case DAYS:
period.setDays(value);
break;
case HOURS:
period.setHours(value);
break;
case MINUTES:
period.setMinutes(value);
break;
case SECONDS:
period.setSeconds(value);
break;
case MILLIS:
period.setMillis(value);
break;
}
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
if (periodStr.regionMatches(true, position, iText, 0, iText.length())) {
return position + iText.length();
}
return ~position;
}
public int parseInto(
ReadWritablePeriod period, String periodStr,
int position, Locale locale) {
PeriodParser[] parsers = iParsers;
if (parsers == null) {
throw new UnsupportedOperationException();
}
int len = parsers.length;
for (int i=0; i<len && position >= 0; i++) {
position = parsers[i].parseInto(period, periodStr, position, locale);
}
return position;
}