Java 8, java.time API. , , API.
Java <= 7, ThreeTen Backport, backport Java 8 . Android ThreeTenABP ( , ).
.
- ( Java 8 - java.time, ThreeTen Backport ( Android ThreeTenABP) - org.threeten.bp), .
, DateTimeFormatter . , . : , , , .
( ) , . getLong ( int), get ( int) , ( , , ).
, , :
String valueWithDate = "00092017";
String pattern = "ddMMyyyy";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern).withResolverStyle(ResolverStyle.STRICT);
TemporalAccessor parsed = fmt.parse(valueWithDate);
int day = (int) parsed.getLong(ChronoField.DAY_OF_MONTH);
if (day == 0) {
day = 1;
}
int month = (int) parsed.getLong(ChronoField.MONTH_OF_YEAR);
if (month == 0) {
month = 1;
}
int year = (int) parsed.getLong(ChronoField.YEAR_OF_ERA);
String value = fmt.format(LocalDate.of(year, month, day));
System.out.println(value);
, 00092017 ddMMyyyy :
01092017
@MenoHochschild, parseUnresolved, , ( ).
java.text.ParsePosition, ( , parse):
// create formatter, no need of strict mode
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern);
// parse
ParsePosition pos = new ParsePosition(0);
TemporalAccessor parsed = fmt.parseUnresolved(valueWithDate, pos);
// check errors
if (pos.getErrorIndex() >= 0) {
// error in parsing (getErrorIndex() returns the index where the error occurred)
}
// rest of the code is the same
@OleV.V. , , , :
if(pos.getIndex() < valueWithDate.length()) {
}
, , ( ).
, , :
DateTimeFormatter output = DateTimeFormatter.ofPattern("MMddyyyy");
String value = output.format(LocalDate.of(year, month, day));
System.out.println(value);