This is an example of how to convert a String type date to a LocalDate type in Java. The background of this investigation is that while implementing an API using Java Persistence API (JPA), This is because it was necessary to convert the character string of yyyyMMdd format stored in String type to LocalDate type.
This post uses Java version 8. The content to be introduced is just an example, so I don't know.
For the time being, create the following method
Sample.java
//Format string date(yyyyMMdd and yyyy/mm/dd etc.)Method to convert to LocalDate type based on
public static LocalDate convertToLocalDate(String date,String format) {
//Simply return the date converted to LocalDate type
return LocalDate.parse(date, DateTimeFormatter.ofPattern(format));
}
Output to check the result
Sample.java
public class Sample {
public static void main (String args[]) {
System.out.println(convertToLocalDate("19990707", "yyyyMMdd"));
}
The output result looks like this
result
1999-07-07
The class DateTimeFormatter seems to have a predefined formatter, Here is an example using that
Sample2.java
//Change arguments to an instance of the string date and DateTimeFormatter classes
public static LocalDate convertStringToLocalDate(String date,DateTimeFormatter formatter) {
return LocalDate.parse(date,formatter);
}
This is the formatter used this time → BASIC_ISO_DATE (The description of "basic ISO date" was on the oracle page) In short, BASIC_ISO_DATE seems to be able to carry a formatter in the form of "yyyymmdd".
Sample2.java
public class Sample2 {
public static void main (String args[]) {
System.out.println(convertStringToLocalDate("18980401", DateTimeFormatter.BASIC_ISO_DATE));
}
The result will be the same as Sample.java
result
1898-04-01
Since this is my first post, I'm new to posting, but I'd like to continue patiently. Advice and suggestions are welcome
Recommended Posts