【发布时间】:2020-10-03 22:20:07
【问题描述】:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.time.*;
import java.time.format.*;
import java.text.*;
public class ConvertStringToDate {
public static void main(String[] args)throws Exception {
String date = "2020-06-14";
DateTimeFormatter Stringformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// convert String to LocalDate
LocalDate localDate = LocalDate.parse(date, Stringformatter);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String formattedDate = localDate.format(formatter); // output here is as expected 14.06.2020
// facing issues when converting back to localDate with defined pattern,
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter); // expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14
// System.out.println(parsedDate);
// System.out.println(parsedDate.getClass().getName());
}
}
为我早期使用 java 的解释道歉。基本上,我试图将输入字符串“2020-06-14”转换为带有自定义模式“dd.MM.yyyy”的localDate,最后尝试使用日期对象而不是字符串。有没有其他方法可以实现它。
【问题讨论】:
-
你不想要那个,或者至少不应该想要那个。
LocalDate属于您的域模型,格式无关紧要。一种特定的格式属于你的界面——并且在一个字符串中。