Java 8 里的日期时间API,新增了 LocalDate、LocalDateTime、LocalTime等线程安全类,本篇文章讲讲字符串到 LocalDate、LocalDateTime 的转换。
LocalDate.parse()
or LocalDateTime.parse()
String armisticeDate = "2019-0510"; LocalDate aLD = LocalDate.parse(armisticeDate); System.out.println("Date: " + aLD); String armisticeDateTime = "2019-0510T11:50"; LocalDateTime aLDT = LocalDateTime.parse(armisticeDateTime); System.out.println("Date/Time: " + aLDT); Output: Date: 2019-0510 Date/Time: 2019-0510T11:50
DateTimeFormatter.ofPattern()
String anotherDate = "10 Apr 2019"; DateTimeFormatter df = DateTimeFormatter.ofPattern("dd MMM yyyy"); LocalDate random = LocalDate.parse(anotherDate, df); System.out.println(anotherDate + " parses as " + random);
我组建了一个技术交流群,里边会有技术大佬一起交流学习,共同成长。需要的朋友可以加我微信(微信ID:yonglun_1994),拉你进群,并有学习大礼包相送。