org.joda.time.format.ISOPeriodFormat Java Examples
The following examples show how to use
org.joda.time.format.ISOPeriodFormat.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IntervalParser.java From crate with Apache License 2.0 | 6 votes |
/** * 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(); }
Example #2
Source File: Literals.java From ldp4j with Apache License 2.0 | 6 votes |
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; }
Example #3
Source File: ISODURATION.java From warp10-platform with Apache License 2.0 | 6 votes |
@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; }
Example #4
Source File: EwsUtilities.java From ews-java-api with MIT License | 6 votes |
/** * 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); }
Example #5
Source File: VectorOutput.java From Bats with Apache License 2.0 | 5 votes |
@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); } }
Example #6
Source File: Result.java From TinCanJava with Apache License 2.0 | 5 votes |
@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; }
Example #7
Source File: XmlDurationObjectFactory.java From ldp4j with Apache License 2.0 | 5 votes |
@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); } }
Example #8
Source File: JodaDurationObjectFactory.java From ldp4j with Apache License 2.0 | 5 votes |
@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); } }
Example #9
Source File: FmtPeriodTest.java From super-csv with Apache License 2.0 | 5 votes |
@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); }
Example #10
Source File: ParsePeriodTest.java From super-csv with Apache License 2.0 | 5 votes |
@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); }
Example #11
Source File: IndexMetadata.java From Raigad with Apache License 2.0 | 5 votes |
@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; }
Example #12
Source File: StringConverter.java From astor with GNU General Public License v2.0 | 5 votes |
/** * 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 + '"'); } }
Example #13
Source File: StringConverter.java From astor with GNU General Public License v2.0 | 5 votes |
/** * 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 + '"'); } }
Example #14
Source File: VectorOutput.java From Bats with Apache License 2.0 | 5 votes |
@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); } }
Example #15
Source File: ADDDURATION.java From warp10-platform with Apache License 2.0 | 5 votes |
/** * 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); }
Example #16
Source File: YouTubeVideo.java From SkyTube with GNU General Public License v3.0 | 4 votes |
public void setDurationInSeconds(String durationInSeconds) { PeriodFormatter formatter = ISOPeriodFormat.standard(); Period p = formatter.parsePeriod(durationInSeconds); this.durationInSeconds = p.toStandardSeconds().getSeconds(); }
Example #17
Source File: BasicJsonOutput.java From Bats with Apache License 2.0 | 4 votes |
@Override public void writeInterval(Period value) throws IOException { gen.writeString(value.toString(ISOPeriodFormat.standard())); }
Example #18
Source File: Literals.java From ldp4j with Apache License 2.0 | 4 votes |
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); }
Example #19
Source File: BasicJsonOutput.java From dremio-oss with Apache License 2.0 | 4 votes |
@Override public void writeInterval(Period value) throws IOException { gen.writeString(value.toString(ISOPeriodFormat.standard())); }
Example #20
Source File: DURATION.java From warp10-platform with Apache License 2.0 | 4 votes |
@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; }
Example #21
Source File: StringConverter.java From astor with GNU General Public License v2.0 | 4 votes |
/** * 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); }
Example #22
Source File: StringConverter.java From astor with GNU General Public License v2.0 | 4 votes |
/** * 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); }
Example #23
Source File: TimePeriod.java From arctic-sea with Apache License 2.0 | 3 votes |
/** * 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); }
Example #24
Source File: PeriodConverter.java From gson-jodatime-serialisers with MIT License | 3 votes |
/** * 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)); }
Example #25
Source File: PeriodConverter.java From gson-jodatime-serialisers with MIT License | 3 votes |
/** * 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()); }
Example #26
Source File: Time_5_Period_t.java From coming with MIT License | 2 votes |
/** * 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()); }
Example #27
Source File: TimeBasedRetentionPolicy.java From incubator-gobblin with Apache License 2.0 | 2 votes |
/** * Since months and years can have arbitrary days, joda time does not allow conversion of a period string containing * months or years to a duration. Hence we calculate the duration using 1970 01:01:00:00:00 UTC as a reference time. * * <p> * <code> * (1970 01:01:00:00:00 + P2Y) - 1970 01:01:00:00:00 = Duration for 2 years * </code> * </p> * * @param periodString * @return duration for this period. */ private static Duration parseDuration(String periodString) { DateTime zeroEpoc = new DateTime(0); return new Duration(zeroEpoc, zeroEpoc.plus(ISOPeriodFormat.standard().parsePeriod(periodString))); }
Example #28
Source File: Time_5_Period_s.java From coming with MIT License | 2 votes |
/** * 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()); }
Example #29
Source File: AbstractPeriod.java From astor with GNU General Public License v2.0 | 2 votes |
/** * 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); }
Example #30
Source File: Period.java From astor with GNU General Public License v2.0 | 2 votes |
/** * 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()); }