How can I parseformat dates with LocalDateTime Java 8
Mistake producing Gemini contented Question & Answer :
Java eight added a fresh java.clip API for running with dates and occasions (JSR 310).
I person day and clip arsenic drawstring (e.g., "2014-04-08 12:30"). However tin I get a LocalDateTime case from the fixed drawstring?
Last I completed running with the LocalDateTime entity: However tin I past person the LocalDateTime case backmost to a drawstring with the aforesaid format arsenic proven supra?
Parsing day and clip
To make a LocalDateTime entity from a drawstring you tin usage the static LocalDateTime.parse() technique. It takes a drawstring and a DateTimeFormatter arsenic parameter. The DateTimeFormatter is utilized to specify the day/clip form.
Drawstring str = "1986-04-08 12:30"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
Formatting day and clip
To make a formatted drawstring retired a LocalDateTime entity you tin usage the format() methodology.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime dateTime = LocalDateTime.of(1986, Period.APRIL, eight, 12, 30); Drawstring formattedDateTime = dateTime.format(formatter); // "1986-04-08 12:30"
Line that location are any generally utilized day/clip codecs predefined arsenic constants successful DateTimeFormatter. For illustration: Utilizing DateTimeFormatter.ISO_DATE_TIME to format the LocalDateTime case from supra would consequence successful the drawstring "1986-04-08T12:30:00".
The parse() and format() strategies are disposable for each day/clip associated objects (e.g. LocalDate oregon ZonedDateTime)