Date synchronization without using a month DateTimeFormatter

I am trying to ddYYYY date with this format: ddYYYY . For example, I have line 141968 , and I want to know that day = 14 and year = 1968 .

I suggest that I should use TemporalAccessor directly provided by DateTimeFormatter.parse(String) , but I cannot find how to use this result. During debugging, I see the result of java.time.Parsed , which is not publicly available but contains the information I want in the fieldValues field.

How can I parse this particular format?

Thanks.

+6
source share
3 answers

One approach is to not have a month field by default:

 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 the TemporalAccessor request:

 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" rather than "Y" for parsing)

+13
source

YYYY creates a WeakBasedYear field that cannot be easily accessed ( https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns ) from TemporalAccessor . You must use the "ddyyyy" or "dduuuu" template with a 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
fourteen

+2
source
 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)); 

conclusion 14/1968

-1
source

Source: https://habr.com/ru/post/985171/


All Articles