English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java complete list of examples
在此程序中,您将学习使用格式化程序将字符串转换为Java中的日期。
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class TimeString { public static void main(String[] args) { //格式化 y-M-d 或 yyyy-MM-d String string = "2017-07-25"; LocalDate date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE); System.out.println(date); } }
When running the program, the output is:
2017-07-25
在上面的程序中,我们使用了预定义的格式化程序ISO_DATE,该格式化程序采用日期字符串,格式为2017-07-25或2017-07-25 + 05:45'。
LocalDate的parse()函数使用给定的格式化程序解析给定的字符串。您也可以在上面的示例中删除ISO_DATE格式化程序,并将parse()方法替换为:
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 running the program, 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.