无法使用自定义模式将字符串转换为 localDate
Unable to Convert String to localDate with custom pattern
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,最后尝试使用日期对象而不是字符串。有没有其他方法可以实现它。
日期没有格式。因此当你写
//expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14
您的期望完全错误。日期根据格式化程序进行解析,但日期如何表示已解析的值以及之后如何选择显示它们不再与格式化程序有任何联系。
恢复格式的唯一方法是再次写入 parsedDate.format(formatter)
,然后您就回到了开始的地方,这就是 formattedDate
已经达到的状态。
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,最后尝试使用日期对象而不是字符串。有没有其他方法可以实现它。
日期没有格式。因此当你写
//expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14
您的期望完全错误。日期根据格式化程序进行解析,但日期如何表示已解析的值以及之后如何选择显示它们不再与格式化程序有任何联系。
恢复格式的唯一方法是再次写入 parsedDate.format(formatter)
,然后您就回到了开始的地方,这就是 formattedDate
已经达到的状态。