本文整理汇总了Java中java.time.format.DateTimeParseException类的典型用法代码示例。如果您正苦于以下问题:Java DateTimeParseException类的具体用法?Java DateTimeParseException怎么用?Java DateTimeParseException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DateTimeParseException类属于java.time.format包,在下文中一共展示了DateTimeParseException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: test_resolveClockHourOfAmPm
import java.time.format.DateTimeParseException; //导入依赖的package包/类
@Test(dataProvider="resolveClockHourOfAmPm")
public void test_resolveClockHourOfAmPm(ResolverStyle style, long value, Integer expectedValue) {
String str = Long.toString(value);
DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_AMPM).toFormatter();
if (expectedValue != null) {
TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
assertEquals(accessor.query(TemporalQueries.localDate()), null);
assertEquals(accessor.query(TemporalQueries.localTime()), null);
assertEquals(accessor.isSupported(CLOCK_HOUR_OF_AMPM), false);
assertEquals(accessor.isSupported(HOUR_OF_AMPM), true);
assertEquals(accessor.getLong(HOUR_OF_AMPM), expectedValue.longValue());
} else {
try {
f.withResolverStyle(style).parse(str);
fail();
} catch (DateTimeParseException ex) {
// expected
}
}
}
示例2: CreatePIMAppointment
import java.time.format.DateTimeParseException; //导入依赖的package包/类
private PIMEntity CreatePIMAppointment(){
System.out.println("Enter date for Appointmen item:(like 04/20/2017):");
LocalDate AppointmenDate = null;
String DateString = sc.nextLine();
try{
AppointmenDate = LocalDate.parse(DateString,DateTimeFormatter.ofPattern("MM/dd/yyyy"));
}
catch(DateTimeParseException e){
System.out.println("Date Format Error, Go Back Create Item.");
return null;
}
System.out.println("Enter date for Appointmen text:");
String TextString = sc.nextLine();
System.out.println("Enter date for Appointmen priority:");
String PriorityString = sc.nextLine();
return new PIMAppointment(TextString, AppointmenDate, PriorityString);
}
示例3: CreatePIMTodo
import java.time.format.DateTimeParseException; //导入依赖的package包/类
private PIMEntity CreatePIMTodo(){
System.out.println("Enter date for todo item:(like 04/20/2017):");
LocalDate TodoDate = null;
String DateString = sc.nextLine();
try{
TodoDate = LocalDate.parse(DateString,DateTimeFormatter.ofPattern("MM/dd/yyyy"));
}
catch(DateTimeParseException e){
System.out.println("Date Format Error, Go Back Create Item.");
return null;
}
System.out.println("Enter date for todo text:");
String TextString = sc.nextLine();
System.out.println("Enter date for todo priority:");
String PriorityString = sc.nextLine();
return new PIMTodo(TextString, TodoDate, PriorityString);
}
示例4: parseFraction
import java.time.format.DateTimeParseException; //导入依赖的package包/类
private static int parseFraction(CharSequence text, int start, int end, int negate) {
// regex limits to [0-9]{0,9}
if (start < 0 || end < 0 || end - start == 0) {
return 0;
}
try {
int fraction = Integer.parseInt(text, start, end, 10);
// for number strings smaller than 9 digits, interpret as if there
// were trailing zeros
for (int i = end - start; i < 9; i++) {
fraction *= 10;
}
return fraction * negate;
} catch (NumberFormatException | ArithmeticException ex) {
throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: fraction", text, 0).initCause(ex);
}
}
示例5: parse
import java.time.format.DateTimeParseException; //导入依赖的package包/类
/**
* Parse a date using the pattern given in parameter or {@link #DATE_FORMAT_STR_ISO8601} and the browser timezone.
*
* @param useBrowserTimezone when the date doesn't include timezone information use browser default or UTC.
* @param pattern pattern to use. If null, {@link #DATE_FORMAT_STR_ISO8601} will be used.
* @param hasTz whether the pattern includes timezone information. when null the pattern will be parsed to search it.
* @param date date to parse
* @return the parsed date
*/
public Date parse(boolean useBrowserTimezone, String pattern, Boolean hasTz, String date) {
if (null == pattern) {
try {
return parse(DefaultDateFormat.DATE_FORMAT_STR_ISO8601, date);
}catch (DateTimeParseException e){
return parse(DefaultDateFormat.DATE_FORMAT_STR_ISO8601_Z, date);
}
} else {
String patternCacheKey = pattern + useBrowserTimezone;
DateParser parser = CACHE_PARSERS.get(patternCacheKey);
if (null == parser) {
boolean patternHasTz = useBrowserTimezone || (hasTz == null ? hasTz(pattern) : hasTz.booleanValue());
if (patternHasTz) {
parser = new DateParser(pattern);
} else {
// the pattern does not have a timezone, we use the UTC timezone as reference
parser = new DateParserNoTz(pattern);
}
CACHE_PARSERS.put(patternCacheKey, parser);
}
return parser.parse(date);
}
}
示例6: test_parse_parseLenientQuarter_SMART
import java.time.format.DateTimeParseException; //导入依赖的package包/类
@Test(dataProvider = "parseLenientQuarter")
public void test_parse_parseLenientQuarter_SMART(String str, LocalDate expected, boolean smart) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(YEAR).appendLiteral(':')
.appendValue(IsoFields.QUARTER_OF_YEAR).appendLiteral(':')
.appendValue(IsoFields.DAY_OF_QUARTER)
.toFormatter().withResolverStyle(ResolverStyle.SMART);
if (smart) {
LocalDate parsed = LocalDate.parse(str, f);
assertEquals(parsed, expected);
} else {
try {
LocalDate.parse(str, f);
fail("Should have failed");
} catch (DateTimeParseException ex) {
// expected
}
}
}
示例7: test_parse_parseLenientWeek_SMART
import java.time.format.DateTimeParseException; //导入依赖的package包/类
@Test(dataProvider = "parseLenientWeek")
public void test_parse_parseLenientWeek_SMART(String str, LocalDate expected, boolean smart) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral(':')
.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral(':')
.appendValue(DAY_OF_WEEK)
.toFormatter().withResolverStyle(ResolverStyle.SMART);
if (smart) {
LocalDate parsed = LocalDate.parse(str, f);
assertEquals(parsed, expected);
} else {
try {
LocalDate.parse(str, f);
fail("Should have failed");
} catch (DateTimeParseException ex) {
// expected
}
}
}
示例8: read
import java.time.format.DateTimeParseException; //导入依赖的package包/类
@Override
public OerGeneralizedTime read(CodecContext context, InputStream inputStream) throws IOException {
Objects.requireNonNull(context);
Objects.requireNonNull(inputStream);
final String timeString = context.read(OerIA5String.class, inputStream).getValue();
if (timeString.length() != 19 || !timeString.endsWith("Z")) {
throw new IllegalArgumentException(
"Interledger GeneralizedTime only supports values in the format 'YYYYMMDDTHHMMSS.fffZ',"
+ " value " + timeString + " is invalid.");
}
try {
final Instant value = Instant.from(generalizedTimeFormatter.parse(timeString));
return new OerGeneralizedTime(value);
} catch (DateTimeParseException dtp) {
throw new IllegalArgumentException(
"Interledger GeneralizedTime only supports values in the format 'YYYYMMDDTHHMMSS.fffZ', "
+ "value " + timeString + " is invalid.",
dtp);
}
}
示例9: getBaseDateFromString
import java.time.format.DateTimeParseException; //导入依赖的package包/类
@VisibleForTesting
Optional<LocalDate> getBaseDateFromString(String text) {
Optional<LocalDate> result = Optional.empty();
Matcher matcher = BASE_DATE_PATTERN.matcher(text);
if (matcher.find()) {
String dateAsString = matcher.group(1);
try {
result = Optional.of(LocalDate.parse(dateAsString, BASE_DATE_FORMATTER));
} catch (DateTimeParseException e) {
log.warn("Failed to parse base date from string: {}", text);
}
} else {
log.warn("Failed to read base date from string: {}", text);
}
return result;
}
示例10: fromString
import java.time.format.DateTimeParseException; //导入依赖的package包/类
public static Optional<FilterInfo> fromString(String text) {
Optional<FilterInfo> result = Optional.empty();
String[] parts = StringUtils.split(text, ',');
if (parts != null && parts.length == 3) {
String value = parts[0];
String mensaId = parts[1];
String dateString = parts[2];
try {
LocalDate date = LocalDate.parse(dateString, DATE_TIME_FORMATTER);
result = Optional.of(FilterInfo.of(value, mensaId, date));
} catch (DateTimeParseException e) {
log.info("Failed to parse local date from \"{}\": {}", dateString, e.getMessage());
}
}
return result;
}
示例11: test_resolveClockHourOfDay
import java.time.format.DateTimeParseException; //导入依赖的package包/类
@Test(dataProvider="resolveClockHourOfDay")
public void test_resolveClockHourOfDay(ResolverStyle style, long value, Integer expectedHour, int expectedDays) {
String str = Long.toString(value);
DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_DAY).toFormatter();
if (expectedHour != null) {
TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
assertEquals(accessor.query(TemporalQueries.localDate()), null);
assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.of(expectedHour, 0));
assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays));
} else {
try {
f.withResolverStyle(style).parse(str);
fail();
} catch (DateTimeParseException ex) {
// expected
}
}
}
示例12: test_resolveFourToTime
import java.time.format.DateTimeParseException; //导入依赖的package包/类
@Test(dataProvider="resolveFourToTime")
public void test_resolveFourToTime(ResolverStyle style,
long hour, long min, long sec, long nano, LocalTime expectedTime, Period excessPeriod) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.parseDefaulting(HOUR_OF_DAY, hour)
.parseDefaulting(MINUTE_OF_HOUR, min)
.parseDefaulting(SECOND_OF_MINUTE, sec)
.parseDefaulting(NANO_OF_SECOND, nano).toFormatter();
ResolverStyle[] styles = (style != null ? new ResolverStyle[] {style} : ResolverStyle.values());
for (ResolverStyle s : styles) {
if (expectedTime != null) {
TemporalAccessor accessor = f.withResolverStyle(s).parse("");
assertEquals(accessor.query(TemporalQueries.localDate()), null, "ResolverStyle: " + s);
assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime, "ResolverStyle: " + s);
assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), excessPeriod, "ResolverStyle: " + s);
} else {
try {
f.withResolverStyle(style).parse("");
fail();
} catch (DateTimeParseException ex) {
// expected
}
}
}
}
示例13: parseTime
import java.time.format.DateTimeParseException; //导入依赖的package包/类
private ZonedDateTime parseTime(String time) {
// TODO : may support more than one format at some point
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
.withZone(ZoneId.systemDefault());
ZonedDateTime zdt = null;
try {
zdt = ZonedDateTime.parse(time, dtf);
} catch (DateTimeParseException e) {
logger.debug("parseTime() failed to parse '" + time + "'");
// throw an exception
// mark as complete (via max iterations?)
}
return zdt;
}
示例14: test_resolveMinuteOfDay
import java.time.format.DateTimeParseException; //导入依赖的package包/类
@Test(dataProvider="resolveMinuteOfDay")
public void test_resolveMinuteOfDay(ResolverStyle style, long value, Integer expectedMinute, int expectedDays) {
String str = Long.toString(value);
DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(MINUTE_OF_DAY).toFormatter();
if (expectedMinute != null) {
TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
assertEquals(accessor.query(TemporalQueries.localDate()), null);
assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.ofSecondOfDay(expectedMinute * 60));
assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays));
} else {
try {
f.withResolverStyle(style).parse(str);
fail();
} catch (DateTimeParseException ex) {
// expected
}
}
}
示例15: parse
import java.time.format.DateTimeParseException; //导入依赖的package包/类
/**
* Obtains an instance of {@code MonthDay} from a text string such as {@code --12-03}.
* <p>
* The string must represent a valid month-day. The format is {@code --MM-dd}.
*
* @param text the text to parse such as "--12-03", not null
* @return the parsed month-day, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static MonthDay parse(CharSequence text) {
int length = text.length();
int errorIndex = 0;
Throwable cause = null;
try {
// "--MM-dd".length() == 7
if ((length == 7) && (text.charAt(0) == '-') && (text.charAt(1) == '-') && (text.charAt(4) == '-')) {
errorIndex = 2;
String monthString = text.subSequence(2, 4).toString();
int month = Integer.parseInt(monthString);
errorIndex = 5;
String dayString = text.subSequence(5, 7).toString();
int day = Integer.parseInt(dayString);
return of(month, day);
}
} catch (RuntimeException e) {
cause = e;
}
throw new DateTimeParseException("Expected format --MM-dd", text, errorIndex, cause);
}