类org.joda.time.format.ISOPeriodFormat源码实例Demo

下面列出了怎么用org.joda.time.format.ISOPeriodFormat的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: warp10-platform   文件: ISODURATION.java
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  Object top = stack.pop();
  
  if (!(top instanceof Long)) {
    throw new WarpScriptException(getName() + " expects a number of time units (LONG) on top of the stack.");
  }
  
  long duration = ((Number) top).longValue();
  
  StringBuffer buf = new StringBuffer();
  ReadablePeriod period = new MutablePeriod(duration / Constants.TIME_UNITS_PER_MS);
  ISOPeriodFormat.standard().getPrinter().printTo(buf, period, Locale.US);

  stack.push(buf.toString());
  
  return stack;
}
 
源代码2 项目: ews-java-api   文件: EwsUtilities.java
/**
 * Takes an xs:duration string as defined by the W3 Consortiums
 * Recommendation "XML Schema Part 2: Datatypes Second Edition",
 * http://www.w3.org/TR/xmlschema-2/#duration, and converts it into a
 * System.TimeSpan structure This method uses the following approximations:
 * 1 year = 365 days 1 month = 30 days Additionally, it only allows for four
 * decimal points of seconds precision.
 *
 * @param xsDuration xs:duration string to convert
 * @return System.TimeSpan structure
 */
public static TimeSpan getXSDurationToTimeSpan(String xsDuration) {
  // TODO: Need to check whether this should be the equivalent or not
  Matcher m = PATTERN_TIME_SPAN.matcher(xsDuration);
  boolean negative = false;
  if (m.find()) {
    negative = true;
  }

  // Removing leading '-'
  if (negative) {
    xsDuration = xsDuration.replace("-P", "P");
  }

  Period period = Period.parse(xsDuration, ISOPeriodFormat.standard());
    
  long retval = period.toStandardDuration().getMillis();
  
  if (negative) {
    retval = -retval;
  }

  return new TimeSpan(retval);

}
 
源代码3 项目: ldp4j   文件: Literals.java
private static <T> DurationLiteral coherceDuration(T value) {
	DurationLiteral duration=null;
	if(value instanceof Duration) {
		duration=of((Duration)value);
	} else if(value instanceof javax.xml.datatype.Duration) {
		duration=of((javax.xml.datatype.Duration)value);
	} else if(value instanceof String) {
		try {
			Period period = ISOPeriodFormat.standard().parsePeriod((String)value);
			duration=of(period.toStandardDuration());
		} catch (Exception e) {
			throw new DatatypeCohercionException(value,Datatypes.DURATION,e);
		}
	} else {
		throw new DatatypeCohercionException(value,Datatypes.DURATION);
	}
	return duration;
}
 
源代码4 项目: crate   文件: IntervalParser.java
/**
 * Parses a period from the given text, returning a new Period.
 * The following text formats are supported:
 * <p>
 * SQL Standard 'Y-M D H:M:S'
 * ISO 8601 'P1Y2M3DT4H5M6S'
 * PostgreSQL '1 year 2 months 3 days 4 hours 5 minutes 6 seconds'
 * Abbreviated PostgreSQL '1 yr 2 mons 3 d 4 hrs 5 mins 6 secs'
 *
 * @param value  text to parse
 * @param start  start of the precision
 * @param end    end of the precision
 * @return parsed value in a Period object
 * @throws IllegalArgumentException if the text does not fulfill any of the format
 */
public static Period apply(String value, @Nullable Precision start, @Nullable Precision end) {
    if (value == null || value.isEmpty() || value.isBlank()) {
        throw new IllegalArgumentException("Invalid interval format  " + value);
    }

    Period result;
    try {
        result = NumericalIntervalParser.apply(value, start, end);
    } catch (IllegalArgumentException e1) {
        try {
            result = roundToPrecision(ISOPeriodFormat.standard().parsePeriod(value), start, end);
        } catch (IllegalArgumentException e2) {
            try {
                result = SQLStandardIntervalParser.apply(value, start, end);
            } catch (IllegalArgumentException e3) {
                result = PGIntervalParser.apply(value, start, end);
            }
        }
    }
    return result.normalizedStandard();
}
 
源代码5 项目: Bats   文件: VectorOutput.java
@Override
public void writeInterval(boolean isNull) throws IOException {
  IntervalWriter intervalWriter = writer.interval();
  if(!isNull){
    final Period p = ISOPeriodFormat.standard().parsePeriod(parser.getValueAsString());
    int months = DateUtilities.monthsFromPeriod(p);
    int days = p.getDays();
    int millis = DateUtilities.periodToMillis(p);
    intervalWriter.writeInterval(months, days, millis);
  }
}
 
源代码6 项目: Bats   文件: VectorOutput.java
@Override
public void writeInterval(boolean isNull) throws IOException {
  IntervalWriter intervalWriter = writer.interval(fieldName);
  if(!isNull){
    final Period p = ISOPeriodFormat.standard().parsePeriod(parser.getValueAsString());
    int months = DateUtilities.monthsFromPeriod(p);
    int days = p.getDays();
    int millis = DateUtilities.periodToMillis(p);
    intervalWriter.writeInterval(months, days, millis);
  }
}
 
源代码7 项目: warp10-platform   文件: ADDDURATION.java
/**
 * 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);
}
 
源代码8 项目: astor   文件: StringConverter.java
/**
 * 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 + '"');
    }
}
 
源代码9 项目: astor   文件: StringConverter.java
/**
 * 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 + '"');
    }
}
 
源代码10 项目: Raigad   文件: IndexMetadata.java
@JsonCreator
public IndexMetadata(
        @JsonProperty("indexName") String indexName,
        @JsonProperty("indexNamePattern") String indexNamePattern,
        @JsonProperty("retentionType") String retentionType,
        @JsonProperty("retentionPeriod") String retentionPeriod,
        @JsonProperty("preCreate") Boolean preCreate) throws UnsupportedAutoIndexException {

    if (retentionType == null) {
        retentionType = "DAILY";
    }
    RETENTION_TYPE retType = RETENTION_TYPE.valueOf(retentionType.toUpperCase());

    // If legacy prefix is used, then quote it so it will be used as plain text in
    // date pattern
    String prefix = (indexName == null) ? "" : "'" + indexName + "'";

    String namePattern = (indexNamePattern == null)
        ? prefix + retType.datePattern
        : indexNamePattern;

    this.indexNamePattern = (indexName == null && indexNamePattern == null)
        ? null
        : namePattern;

    this.formatter = DateTimeFormat.forPattern(namePattern).withZoneUTC();
    this.indexNameFilter = new DatePatternIndexNameFilter(formatter);

    if (retentionPeriod == null) {
        this.retentionPeriod = null;
    } else if (retentionPeriod.startsWith("P")) {
        this.retentionPeriod = ISOPeriodFormat.standard().parsePeriod(retentionPeriod);
    } else {
        Integer num = Integer.parseInt(retentionPeriod);
        String period = String.format(retType.periodFormat, num);
        this.retentionPeriod = ISOPeriodFormat.standard().parsePeriod(period);
    }

    this.preCreate = preCreate == null ? false : preCreate;
}
 
源代码11 项目: super-csv   文件: ParsePeriodTest.java
@Before
public void setUp() {
	formatter = ISOPeriodFormat.standard();
	processor1 = new ParsePeriod();
	processor2 = new ParsePeriod(formatter);
	processorChain1 = new ParsePeriod(new IdentityTransform());
	processorChain2 = new ParsePeriod(formatter, new IdentityTransform());
	processors = Arrays.asList(processor1, processor2, processorChain1,
			processorChain2);
}
 
源代码12 项目: super-csv   文件: FmtPeriodTest.java
@Before
public void setUp() {
	formatter = ISOPeriodFormat.standard();
	processor1 = new FmtPeriod();
	processor2 = new FmtPeriod(formatter);
	processorChain1 = new FmtPeriod(new IdentityTransform());
	processorChain2 = new FmtPeriod(formatter, new IdentityTransform());
	processors = Arrays.asList(processor1, processor2, processorChain1,
			processorChain2);
}
 
源代码13 项目: ldp4j   文件: JodaDurationObjectFactory.java
@Override
public Duration fromString(String rawValue) {
	try {
		Period period = ISOPeriodFormat.standard().parsePeriod(rawValue);
		return period.toStandardDuration();
	} catch (Exception e) {
		throw new ObjectParseException(e,Duration.class,rawValue);
	}
}
 
源代码14 项目: ldp4j   文件: XmlDurationObjectFactory.java
@Override
public Duration fromString(String rawValue) {
	try {
		Period period = ISOPeriodFormat.standard().parsePeriod(rawValue);
		return TimeUtils.newInstance().from(period.toStandardDuration()).toDuration();
	} catch (Exception e) {
		throw new ObjectParseException(e,Duration.class,rawValue);
	}
}
 
源代码15 项目: TinCanJava   文件: Result.java
@Override
public ObjectNode toJSONNode(TCAPIVersion version) {
    ObjectMapper mapper = Mapper.getInstance();
    ObjectNode node = mapper.createObjectNode();

    if (this.score != null) {
        node.put("score", this.getScore().toJSONNode(version));
    }
    if (this.success != null) {
        node.put("success", this.getSuccess());
    }
    if (this.completion != null) {
        node.put("completion", this.getCompletion());
    }
    if (this.duration != null) {
        //
        // ISOPeriodFormat includes milliseconds but the spec only allows
        // hundredths of a second here, so get the normal string, then truncate
        // the last digit to provide the proper precision
        //
        String shortenedDuration = ISOPeriodFormat.standard().print(this.getDuration()).replaceAll("(\\.\\d\\d)\\dS", "$1S");

        node.put("duration", shortenedDuration);
    }
    if (this.response != null) {
        node.put("response", this.getResponse());
    }
    if (this.extensions != null) {
        node.put("extensions", this.getExtensions().toJSONNode(version));
    }

    return node;
}
 
源代码16 项目: Bats   文件: BasicJsonOutput.java
@Override
public void writeInterval(Period value) throws IOException {
  gen.writeString(value.toString(ISOPeriodFormat.standard()));
}
 
源代码17 项目: dremio-oss   文件: BasicJsonOutput.java
@Override
public void writeInterval(Period value) throws IOException {
  gen.writeString(value.toString(ISOPeriodFormat.standard()));
}
 
源代码18 项目: warp10-platform   文件: DURATION.java
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  
  Object o = stack.pop();
  
  if (!(o instanceof String)) {
    throw new WarpScriptException(getName() + " expects an ISO8601 duration (a string) on top of the stack. See http://en.wikipedia.org/wiki/ISO_8601#Durations");
  }

  // Separate seconds from digits below second precision
  String duration_string = o.toString();
  String[] tokens = UnsafeString.split(duration_string, '.');

  long offset = 0;
  if (tokens.length > 2) {
    throw new WarpScriptException(getName() + "received an invalid ISO8601 duration.");
  }

  if (2 == tokens.length) {
    duration_string = tokens[0].concat("S");
    String tmp = tokens[1].substring(0, tokens[1].length() - 1);
    Double d_offset = Double.valueOf("0." + tmp) * STU;
    offset = d_offset.longValue();
  }
  
  ReadWritablePeriod period = new MutablePeriod();
  
  ISOPeriodFormat.standard().getParser().parseInto(period, duration_string, 0, Locale.US);

  Period p = period.toPeriod();
  
  if (p.getMonths() != 0 || p.getYears() != 0) {
    throw new WarpScriptException(getName() + " doesn't support ambiguous durations containing years or months, please convert those to days.");
  }

  Duration duration = p.toDurationFrom(new Instant());

  // check if offset should be positive of negative
  if (p.getSeconds() < 0) {
    offset = -offset;
  }

  stack.push(duration.getMillis() * Constants.TIME_UNITS_PER_MS + offset);

  return stack;
}
 
源代码19 项目: SkyTube   文件: YouTubeVideo.java
public void setDurationInSeconds(String durationInSeconds) {
	PeriodFormatter formatter = ISOPeriodFormat.standard();
	Period p = formatter.parsePeriod(durationInSeconds);
	this.durationInSeconds = p.toStandardSeconds().getSeconds();
}
 
源代码20 项目: astor   文件: StringConverter.java
/**
 * Sets the value of the mutable interval from the string.
 * 
 * @param writableInterval  the interval to set
 * @param object  the String to convert, must not be null
 * @param chrono  the chronology to use, may be null
 */
public void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono) {
    String str = (String) object;

    int separator = str.indexOf('/');
    if (separator < 0) {
        throw new IllegalArgumentException("Format requires a '/' separator: " + str);
    }

    String leftStr = str.substring(0, separator);
    if (leftStr.length() <= 0) {
        throw new IllegalArgumentException("Format invalid: " + str);
    }
    String rightStr = str.substring(separator + 1);
    if (rightStr.length() <= 0) {
        throw new IllegalArgumentException("Format invalid: " + str);
    }

    DateTimeFormatter dateTimeParser = ISODateTimeFormat.dateTimeParser();
    dateTimeParser = dateTimeParser.withChronology(chrono);
    PeriodFormatter periodParser = ISOPeriodFormat.standard();
    long startInstant = 0, endInstant = 0;
    Period period = null;
    Chronology parsedChrono = null;
    
    // before slash
    char c = leftStr.charAt(0);
    if (c == 'P' || c == 'p') {
        period = periodParser.withParseType(getPeriodType(leftStr)).parsePeriod(leftStr);
    } else {
        DateTime start = dateTimeParser.parseDateTime(leftStr);
        startInstant = start.getMillis();
        parsedChrono = start.getChronology();
    }
    
    // after slash
    c = rightStr.charAt(0);
    if (c == 'P' || c == 'p') {
        if (period != null) {
            throw new IllegalArgumentException("Interval composed of two durations: " + str);
        }
        period = periodParser.withParseType(getPeriodType(rightStr)).parsePeriod(rightStr);
        chrono = (chrono != null ? chrono : parsedChrono);
        endInstant = chrono.add(period, startInstant, 1);
    } else {
        DateTime end = dateTimeParser.parseDateTime(rightStr);
        endInstant = end.getMillis();
        parsedChrono = (parsedChrono != null ? parsedChrono : end.getChronology());
        chrono = (chrono != null ? chrono : parsedChrono);
        if (period != null) {
            startInstant = chrono.add(period, endInstant, -1);
        }
    }
    
    writableInterval.setInterval(startInstant, endInstant);
    writableInterval.setChronology(chrono);
}
 
源代码21 项目: astor   文件: StringConverter.java
/**
 * Sets the value of the mutable interval from the string.
 * 
 * @param writableInterval  the interval to set
 * @param object  the String to convert, must not be null
 * @param chrono  the chronology to use, may be null
 */
public void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono) {
    String str = (String) object;

    int separator = str.indexOf('/');
    if (separator < 0) {
        throw new IllegalArgumentException("Format requires a '/' separator: " + str);
    }

    String leftStr = str.substring(0, separator);
    if (leftStr.length() <= 0) {
        throw new IllegalArgumentException("Format invalid: " + str);
    }
    String rightStr = str.substring(separator + 1);
    if (rightStr.length() <= 0) {
        throw new IllegalArgumentException("Format invalid: " + str);
    }

    DateTimeFormatter dateTimeParser = ISODateTimeFormat.dateTimeParser();
    dateTimeParser = dateTimeParser.withChronology(chrono);
    PeriodFormatter periodParser = ISOPeriodFormat.standard();
    long startInstant = 0, endInstant = 0;
    Period period = null;
    Chronology parsedChrono = null;
    
    // before slash
    char c = leftStr.charAt(0);
    if (c == 'P' || c == 'p') {
        period = periodParser.withParseType(getPeriodType(leftStr)).parsePeriod(leftStr);
    } else {
        DateTime start = dateTimeParser.parseDateTime(leftStr);
        startInstant = start.getMillis();
        parsedChrono = start.getChronology();
    }
    
    // after slash
    c = rightStr.charAt(0);
    if (c == 'P' || c == 'p') {
        if (period != null) {
            throw new IllegalArgumentException("Interval composed of two durations: " + str);
        }
        period = periodParser.withParseType(getPeriodType(rightStr)).parsePeriod(rightStr);
        chrono = (chrono != null ? chrono : parsedChrono);
        endInstant = chrono.add(period, startInstant, 1);
    } else {
        DateTime end = dateTimeParser.parseDateTime(rightStr);
        endInstant = end.getMillis();
        parsedChrono = (parsedChrono != null ? parsedChrono : end.getChronology());
        chrono = (chrono != null ? chrono : parsedChrono);
        if (period != null) {
            startInstant = chrono.add(period, endInstant, -1);
        }
    }
    
    writableInterval.setInterval(startInstant, endInstant);
    writableInterval.setChronology(chrono);
}
 
源代码22 项目: ldp4j   文件: Literals.java
public static DurationLiteral of(javax.xml.datatype.Duration duration) {
	checkNotNull(duration,DURATION_CANNOT_BE_NULL);
	Period period = ISOPeriodFormat.standard().parsePeriod(duration.toString());
	return new ImmutableDurationLiteral(period.toStandardDuration(),Datatypes.DURATION);
}
 
源代码23 项目: arctic-sea   文件: TimePeriod.java
/**
 * standard constructor
 *
 * @param start
 *            timeString of start position in ISO8601 format
 * @param startIndet
 *            indeterminate time position of start
 * @param end
 *            timeString of end position in ISO8601 format
 * @param endIndet
 *            indeterminate time value of end position
 * @param duration
 *            duration in ISO8601 format
 * @param id
 *            the optional GML id
 * @throws ParseException
 *             if parsing the time strings of start or end into
 *             java.util.Date failed
 */
public TimePeriod(
        DateTime start, IndeterminateValue startIndet, DateTime end, IndeterminateValue endIndet, String duration,
        String id) throws ParseException {
    super(id);
    this.start = start;
    this.startIndet = startIndet;
    this.end = end;
    this.endIndet = endIndet;
    this.duration = ISOPeriodFormat.standard().parsePeriod(duration);
}
 
/**
 * Gson invokes this call-back method during serialization when it encounters a field of the
 * specified type. <p>
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any
 * non-trivial field of the {@code src} object. However, you should never invoke it on the
 * {@code src} object itself since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param src the object that needs to be converted to Json.
 * @param typeOfSrc the actual type (fully genericized version) of the source object.
 * @return a JsonElement corresponding to the specified object.
 */
@Override
public JsonElement serialize(Period src, Type typeOfSrc, JsonSerializationContext context)
{
  final PeriodFormatter fmt = ISOPeriodFormat.standard();
  return new JsonPrimitive(fmt.print(src));
}
 
/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public Period deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException
{
  // Do not try to deserialize null or empty values
  if (json.getAsString() == null || json.getAsString().isEmpty())
  {
    return null;
  }
  final PeriodFormatter fmt = ISOPeriodFormat.standard();
  return fmt.parsePeriod(json.getAsString());
}
 
源代码26 项目: arctic-sea   文件: Times.java
/**
 * Parse a duration from a string representation.
 *
 * @param period Duration as String
 *
 * @return Period object of duration
 */
public static Period decodePeriod(String period) {
    return ISOPeriodFormat.standard().parsePeriod(period);
}
 
源代码27 项目: coming   文件: Time_5_Period_s.java
/**
 * Parses a {@code Period} from the specified string.
 * <p>
 * This uses {@link ISOPeriodFormat#standard()}.
 * 
 * @param str  the string to parse, not null
 * @since 2.0
 */
@FromString
public static Period parse(String str) {
    return parse(str, ISOPeriodFormat.standard());
}
 
源代码28 项目: coming   文件: Time_5_Period_t.java
/**
 * Parses a {@code Period} from the specified string.
 * <p>
 * This uses {@link ISOPeriodFormat#standard()}.
 * 
 * @param str  the string to parse, not null
 * @since 2.0
 */
@FromString
public static Period parse(String str) {
    return parse(str, ISOPeriodFormat.standard());
}
 
源代码29 项目: astor   文件: MutablePeriod.java
/**
 * Parses a {@code MutablePeriod} from the specified string.
 * <p>
 * This uses {@link ISOPeriodFormat#standard()}.
 * 
 * @param str  the string to parse, not null
 * @since 2.0
 */
@FromString
public static MutablePeriod parse(String str) {
    return parse(str, ISOPeriodFormat.standard());
}
 
源代码30 项目: astor   文件: AbstractPeriod.java
/**
 * Gets the value as a String in the ISO8601 duration format.
 * <p>
 * For example, "PT6H3M7S" represents 6 hours, 3 minutes, 7 seconds.
 * <p>
 * For more control over the output, see
 * {@link org.joda.time.format.PeriodFormatterBuilder PeriodFormatterBuilder}.
 *
 * @return the value as an ISO8601 string
 */
@ToString
public String toString() {
    return ISOPeriodFormat.standard().print(this);
}
 
 类所在包
 同包方法