Reputation: 1855
I try to parse a date with this format: ddYYYY
. For example, I have the string 141968
, and I want to know that day = 14
and year = 1968
.
I suppose I have to use directly a TemporalAccessor
gave by DateTimeFormatter.parse(String)
, but I cannot find how to use this result. While debugging I see the result is a java.time.Parsed
which is not public but contains informations I want in field fieldValues
.
How can I parse this particular format?
Thank you.
Upvotes: 6
Views: 5931
Reputation: 892
SimpleDateFormat sdf = new SimpleDateFormat("ddyyyy");
Date DateToStr = sdf.parse("141968");// To convert to date Date object
sdf = new SimpleDateFormat("dd/yyyy"); // Separating by '/'
System.out.println(sdf.format(DateToStr));
output 14/1968
Upvotes: -1
Reputation: 10241
YYYY
produces a WeakBasedYear field which cannot be accessed that easily (https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns) from TemporalAccessor
.
You have to use the pattern "ddyyyy" or "dduuuu" with DateTimeFormatter
to use ChronoField.YEAR
:
TemporalAccessor parsed = DateTimeFormatter.ofPattern("ddyyyy").parse("141968");
System.out.println(parsed.get(ChronoField.YEAR));
System.out.println(parsed.get(ChronoField.DAY_OF_MONTH));
Output:
1968
14
Upvotes: 2
Reputation: 63385
One approach is to default the missing month field:
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern("ddyyyy")
.parseDefaulting(MONTH_OF_YEAR, 1)
.toFormatter();
LocalDate date = LocalDate.parse("141968", f);
System.out.println(date.getDayOfMonth());
System.out.println(date.getYear());
Another is to query the TemporalAccessor
:
DateTimeFormatter f = DateTimeFormatter.ofPattern("ddyyyy");
TemporalAccessor parsed = f.parse("141968");
System.out.println(parsed.get(ChronoField.YEAR));
System.out.println(parsed.get(ChronoField.DAY_OF_MONTH));
(Note the use of "y", not "Y" for parsing)
Upvotes: 16