本文整理了Java中java.time.format.DateTimeFormatter.parseBest()
方法的一些代码示例,展示了DateTimeFormatter.parseBest()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。DateTimeFormatter.parseBest()
方法的具体详情如下:
包路径:java.time.format.DateTimeFormatter
类名称:DateTimeFormatter
方法名:parseBest
[英]Fully parses the text producing an object of one of the specified types.
This parse method is convenient for use when the parser can handle optional elements. For example, a pattern of 'yyyy[-MM[-dd]]' can be fully parsed to a LocalDate, or partially parsed to a YearMonth or a Year. The types must be specified in order, starting from the best matching full-parse option and ending with the worst matching minimal parse option.
The result is associated with the first type that successfully parses. Normally, applications will use instanceof to check the result. For example:
TemporalAccessor dt = parser.parseBest(str, LocalDate.class, YearMonth.class);
if (dt instanceof LocalDate) {
...
} else {
...
}
If the parse completes without reading the entire length of the text, or a problem occurs during parsing or merging, then an exception is thrown.
[中]完全解析生成指定类型之一的对象的文本。
当解析器可以处理可选元素时,使用此解析方法很方便。例如,“yyyy[-MM[-dd]]”模式可以完全解析为LocalDate,也可以部分解析为YearMonth或Year。必须按顺序指定类型,从最佳匹配的完整解析选项开始,以最差匹配的最小解析选项结束。
结果与成功解析的第一个类型相关联。通常,应用程序将使用instanceof检查结果。例如:
TemporalAccessor dt = parser.parseBest(str, LocalDate.class, YearMonth.class);
if (dt instanceof LocalDate) {
...
} else {
...
}
如果解析完成时没有读取整个文本长度,或者在解析或合并过程中出现问题,则会引发异常。
代码示例来源:origin: confluentinc/ksql
public long parse(final String text, final ZoneId zoneId) {
TemporalAccessor parsed = formatter.parseBest(
text,
ZonedDateTime::from,
LocalDateTime::from);
if (parsed == null) {
throw new KsqlException("text value: "
+ text
+ "cannot be parsed into a timestamp");
}
if (parsed instanceof LocalDateTime) {
parsed = ((LocalDateTime) parsed).atZone(zoneId);
}
final LocalDateTime dateTime = ((ZonedDateTime) parsed)
.withZoneSameInstant(ZoneId.systemDefault())
.toLocalDateTime();
return Timestamp.valueOf(dateTime).getTime();
}
代码示例来源:origin: com.impossibl.pgjdbc-ng/pgjdbc-ng
@Override
public TemporalAccessor parse(CharSequence text) {
return FMT_ERA.parseBest(text, ZonedDateTime::from, OffsetDateTime::from, LocalDateTime::from);
}
代码示例来源:origin: org.omnifaces/omniutils
static TemporalAccessor getTemporalAccessor(Object object) {
if (object instanceof TemporalAccessor) {
return (TemporalAccessor) object;
}
if (object instanceof Date) {
return ((Date) object).toInstant();
}
if (object instanceof Long) {
return ofEpochMilli((Long) object);
}
if (object instanceof String) {
return PARSING_DATE_TIME_FORMATTER.parseBest((String)object, ZonedDateTime::from, LocalDateTime::from, LocalDate::from, LocalTime::from);
}
throw new IllegalArgumentException(object + " is not of a valid temporal type");
}
代码示例来源:origin: inspire-software/yes-cart
private static LocalDateTime ldtParse(final String datetime, final DateTimeFormatter formatter) {
if (StringUtils.isNotBlank(datetime)) {
try {
TemporalAccessor temporalAccessor = formatter.parseBest(datetime, LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof LocalDateTime) {
return (LocalDateTime) temporalAccessor;
}
return ((LocalDate) temporalAccessor).atStartOfDay();
} catch (Exception exp) {
LOG.error("Unable to parse date {} using formatter {}", datetime, formatter);
LOG.error(exp.getMessage(), exp);
}
}
return null;
}
代码示例来源:origin: inspire-software/yes-cart
private static LocalDate ldParse(final String datetime, final DateTimeFormatter formatter) {
if (StringUtils.isNotBlank(datetime)) {
try {
TemporalAccessor temporalAccessor = formatter.parseBest(datetime, LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof LocalDateTime) {
return ((LocalDateTime) temporalAccessor).toLocalDate();
}
return (LocalDate) temporalAccessor;
} catch (Exception exp) {
LOG.error("Unable to parse date {} using formatter {}", datetime, formatter);
LOG.error(exp.getMessage(), exp);
}
}
return null;
}
代码示例来源:origin: sitewhere/sitewhere
/**
* Parses a date string using many potential formats. Copied from
* http://stackoverflow.com/questions/34637626/java-datetimeformatter-for-time-zone-with-an-optional-colon-separator
*
* @param date
* @return
* @throws DateTimeParseException
*/
public static ZonedDateTime parseDateInMutipleFormats(String date) throws DateTimeParseException {
TemporalAccessor temporalAccessor = FORMATTER.parseBest(date, ZonedDateTime::from, LocalDateTime::from,
LocalDate::from);
if (temporalAccessor instanceof ZonedDateTime) {
return ((ZonedDateTime) temporalAccessor);
}
if (temporalAccessor instanceof LocalDateTime) {
return ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault());
}
return ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault());
}
代码示例来源:origin: com.sitewhere/sitewhere-core
/**
* Parses a date string using many potential formats. Copied from
* http://stackoverflow.com/questions/34637626/java-datetimeformatter-for-time-zone-with-an-optional-colon-separator
*
* @param date
* @return
* @throws DateTimeParseException
*/
public static ZonedDateTime parseDateInMutipleFormats(String date) throws DateTimeParseException {
TemporalAccessor temporalAccessor = FORMATTER.parseBest(date, ZonedDateTime::from, LocalDateTime::from,
LocalDate::from);
if (temporalAccessor instanceof ZonedDateTime) {
return ((ZonedDateTime) temporalAccessor);
}
if (temporalAccessor instanceof LocalDateTime) {
return ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault());
}
return ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault());
}
代码示例来源:origin: logzio/sawmill
private ZonedDateTime getZonedDateTime(String value, DateTimeFormatter formatter) {
TemporalAccessor temporal = formatter.parseBest(value, ZonedDateTime::from, LocalDateTime::from);
if (temporal instanceof LocalDateTime) {
if (timeZone == null) {
return ZonedDateTime.of((LocalDateTime) temporal, ZoneOffset.UTC);
} else {
return ZonedDateTime.of((LocalDateTime) temporal, timeZone);
}
} else {
return ZonedDateTime.from(temporal);
}
}
代码示例来源:origin: apache/sis
/**
* Parses the given date and/or time, which may have an optional timezone. This method applies heuristic rules
* for choosing if the object should be returned as a local date, or a date and time with timezone, <i>etc</i>.
* The full date format is of the form "1970-01-01T00:00:00.000Z", but this method also accepts spaces in place
* of 'T' as in "1970-01-01 00:00:00".
*
* @param text the character string to parse, or {@code null}.
* @return a temporal object for the given text, or {@code null} if the given text was null.
* @throws DateTimeParseException if the text can not be parsed as a date.
*
* @since 0.8
*/
public static Temporal parseBest(final CharSequence text) {
// Cast is safe if all QUERIES elements return a Temporal subtype.
return (text != null) ? (Temporal) FORMAT.parseBest(toISO(text, 0, text.length()), QUERIES) : null;
}
代码示例来源:origin: io.krakens/java-grok
@Override
public Instant convert(String value) {
TemporalAccessor dt = formatter
.parseBest(value.trim(), ZonedDateTime::from, LocalDateTime::from, OffsetDateTime::from, Instant::from,
LocalDate::from);
if (dt instanceof ZonedDateTime) {
return ((ZonedDateTime) dt).toInstant();
} else if (dt instanceof LocalDateTime) {
return ((LocalDateTime) dt).atZone(timeZone).toInstant();
} else if (dt instanceof OffsetDateTime) {
return ((OffsetDateTime) dt).atZoneSameInstant(timeZone).toInstant();
} else if (dt instanceof Instant) {
return ((Instant) dt);
} else if (dt instanceof LocalDate) {
return ((LocalDate) dt).atStartOfDay(timeZone).toInstant();
} else {
return null;
}
}
代码示例来源:origin: org.graylog2.repackaged/grok
@Override
public Instant convert(String value) {
TemporalAccessor dt = formatter.parseBest(value.trim(), ZonedDateTime::from, LocalDateTime::from, OffsetDateTime::from, Instant::from, LocalDate::from);
if (dt instanceof ZonedDateTime) {
return ((ZonedDateTime)dt).toInstant();
} else if (dt instanceof LocalDateTime) {
return ((LocalDateTime) dt).atZone(timeZone).toInstant();
} else if (dt instanceof OffsetDateTime) {
return ((OffsetDateTime) dt).atZoneSameInstant(timeZone).toInstant();
} else if (dt instanceof Instant) {
return ((Instant) dt);
} else if (dt instanceof LocalDate) {
return ((LocalDate) dt).atStartOfDay(timeZone).toInstant();
} else {
return null;
}
}
代码示例来源:origin: inspire-software/yes-cart
private static ZonedDateTime zdtParse(final String datetime, final DateTimeFormatter formatter) {
if (StringUtils.isNotBlank(datetime)) {
try {
TemporalAccessor temporalAccessor = formatter.parseBest(datetime, LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof LocalDateTime) {
return ((LocalDateTime) temporalAccessor).atZone(zone());
}
return ((LocalDate) temporalAccessor).atStartOfDay(zone());
} catch (Exception exp) {
LOG.error("Unable to parse date {} using formatter {}", datetime, formatter);
LOG.error(exp.getMessage(), exp);
}
}
return null;
}
代码示例来源:origin: thekrakken/java-grok
@Override
public Instant convert(String value) {
TemporalAccessor dt = formatter
.parseBest(value.trim(), ZonedDateTime::from, LocalDateTime::from, OffsetDateTime::from, Instant::from,
LocalDate::from);
if (dt instanceof ZonedDateTime) {
return ((ZonedDateTime) dt).toInstant();
} else if (dt instanceof LocalDateTime) {
return ((LocalDateTime) dt).atZone(timeZone).toInstant();
} else if (dt instanceof OffsetDateTime) {
return ((OffsetDateTime) dt).atZoneSameInstant(timeZone).toInstant();
} else if (dt instanceof Instant) {
return ((Instant) dt);
} else if (dt instanceof LocalDate) {
return ((LocalDate) dt).atStartOfDay(timeZone).toInstant();
} else {
return null;
}
}
代码示例来源:origin: OpenWiseSolutions/openhub-framework
@Nullable
public static OffsetDateTime parseDateTime(@Nullable String dtStr) {
if (dtStr == null) {
return null;
}
// An unspecified time zone is exactly that - unspecified. No more, no less. It's not saying it's in UTC,
// nor is it saying it's in the local time zone or any other time zone, it's just saying that the time
// read from some clock somewhere was that time
// see http://stackoverflow.com/questions/20670041/what-is-the-default-time-zone-for-an-xml-schema-datetime-if-not-specified
// => we use default time zone to the current time
TemporalAccessor dt = DateTimeFormatter.ISO_DATE_TIME.parseBest(dtStr, OffsetDateTime::from, LocalDateTime::from);
if (dt instanceof OffsetDateTime) {
return (OffsetDateTime) dt;
} else {
return OffsetDateTime.of((LocalDateTime)dt, ZoneOffset.from(ZonedDateTime.now()));
}
}
代码示例来源:origin: ai.grakn/grakn-graql
private String convertDateFormat(String originalDate, String originalFormat){
originalFormat = removeQuotes(originalFormat);
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(originalFormat);
TemporalAccessor parsedDate = formatter.parseBest(
originalDate, LocalDateTime::from, LocalDate::from, LocalTime::from);
return extractLocalDateTime(parsedDate).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
} catch (IllegalArgumentException e){
throw GraqlQueryException.cannotParseDateFormat(originalFormat);
} catch (DateTimeParseException e){
throw GraqlQueryException.cannotParseDateString(originalDate, originalFormat, e);
}
}
代码示例来源:origin: OpenWiseSolutions/openhub-framework
@Nullable
public static OffsetDateTime parseDate(@Nullable String dateStr) {
if (dateStr == null) {
return null;
}
// parsing has two steps:
// 1) parse date with offset "2013-10-05+02:00"
// 2) parse date without offset "2013-10-05"
try {
return OffsetDateTime.from(ISO_OFFSET_DATE_MIDNIGHT.parse(dateStr));
} catch (DateTimeParseException ex) {
TemporalAccessor dt = DateTimeFormatter.ISO_DATE.parseBest(dateStr, OffsetDateTime::from, LocalDate::from);
if (dt instanceof OffsetDateTime) {
return (OffsetDateTime) dt;
} else {
LocalDateTime ldt = LocalDateTime.of((LocalDate)dt, LocalTime.now());
return OffsetDateTime.of(ldt.truncatedTo(ChronoUnit.DAYS), ZoneOffset.from(ZonedDateTime.now()));
}
}
}
代码示例来源:origin: it.unibz.inf.ontop/ontop-system-sql-core
private TemporalAccessor convertToTime(Object value) throws OntopResultConversionException {
TemporalAccessor timeValue = null;
if (value instanceof Date ) {
// If JDBC gives us proper Java object, we simply return the formatted version of the datatype
Calendar calendar = DateUtils.toCalendar(((Date) value));
TimeZone timeZone = calendar.getTimeZone();
timeValue = OffsetTime.from(calendar.toInstant().atZone(timeZone.toZoneId()));
} else {
// Otherwise, we need to deal with possible String representation of datetime
String stringValue = String.valueOf(value);
for (DateTimeFormatter format : system2TimeFormatter.get(DEFAULT)) {
try {
timeValue = format.parseBest(stringValue, OffsetTime::from, LocalTime::from);
break;
} catch (DateTimeParseException e) {
// continue with the next try
}
}
if (timeValue == null) {
throw new OntopResultConversionException("unparseable time: " + stringValue);
}
}
return timeValue;
}
代码示例来源:origin: org.threeten/threeten-extra
private static Interval parseEndDateTime(Instant start, ZoneOffset offset, CharSequence endStr) {
try {
TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest(endStr, OffsetDateTime::from, LocalDateTime::from);
if (temporal instanceof OffsetDateTime) {
OffsetDateTime odt = (OffsetDateTime) temporal;
return Interval.of(start, odt.toInstant());
} else {
// infer offset from start if not specified by end
LocalDateTime ldt = (LocalDateTime) temporal;
return Interval.of(start, ldt.toInstant(offset));
}
} catch (DateTimeParseException ex) {
Instant end = Instant.parse(endStr);
return Interval.of(start, end);
}
}
代码示例来源:origin: org.kie/kie-dmn-feel
public FEELFnResult<TemporalAccessor> invoke(@ParameterName( "from" ) String val) {
if ( val == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
if (!DateFunction.BEGIN_YEAR.matcher(val).find()) { // please notice the regex strictly requires the beginning, so we can use find.
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "year not compliant with XML Schema Part 2 Datatypes"));
}
try {
if( val.contains( "T" ) ) {
return FEELFnResult.ofResult(FEEL_DATE_TIME.parseBest(val, ZonedDateTime::from, OffsetDateTime::from, LocalDateTime::from));
} else {
TemporalAccessor value = DateTimeFormatter.ISO_DATE.parse( val, LocalDate::from );
return FEELFnResult.ofResult( LocalDateTime.of( (LocalDate)value, LocalTime.of( 0, 0 ) ) );
}
} catch ( Exception e ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "date-parsing exception", e));
}
}
代码示例来源:origin: apache/sis
/**
* Parses the given date as an instant, assuming UTC timezone if unspecified.
*
* @param text the text to parse as an instant in UTC timezone by default.
* @param lower index of the first character to parse.
* @param upper index after the last character to parse.
* @return the instant for the given text.
* @throws DateTimeParseException if the text can not be parsed as a date.
*/
public static Instant parseInstantUTC(final CharSequence text, final int lower, final int upper) {
TemporalAccessor date = FORMAT.parseBest(toISO(text, lower, upper), QUERIES);
if (date instanceof Instant) {
return (Instant) date;
}
final OffsetDateTime time;
if (date instanceof LocalDateTime) {
time = ((LocalDateTime) date).atOffset(ZoneOffset.UTC);
} else {
time = ((LocalDate) date).atTime(MIDNIGHT);
}
return time.toInstant();
}
内容来源于网络,如有侵权,请联系作者删除!