English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use formatters to convert strings to dates in Java.
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class TimeString { public static void main(String[] args) { //Format y-M-d or yyyy-MM-d String string = "2017-07-25"; LocalDate date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE); System.out.println(date); } }
When the program is run, the output is:
2017-07-25
In the above program, we used the predefined formatter ISO_DATE, which takes date strings in the format2017-07-25or2017-07-25 + 05:45''
The parse() function of LocalDate uses the given formatter to parse the given string. You can also remove the ISO_DATE formatter in the above example and replace the parse() method with:
LocalDate date = LocalDate.parse(string, DateTimeFormatter);
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Locale; public class TimeString { public static void main(String[] args) { String string = "July" 25, 2017"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH); LocalDate date = LocalDate.parse(string, formatter); System.out.println(date); } }
When the program is run, the output is:
2017-07-25
In the above program, our date format is MMMM d, yyyy. Therefore, we created a formatter with the given pattern.
Now, we can use the LocalDate.parse() function to parse the date and obtain a LocalDate object.