【问题标题】:Unable to Convert String to localDate with custom pattern [duplicate]无法使用自定义模式将字符串转换为 localDate [重复]
【发布时间】: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 属于您的域模型,格式无关紧要。一种特定的格式属于你的界面——并且在一个字符串中。

标签: java localdate


【解决方案1】:

日期没有格式。因此,当你写

//expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14

您的期望完全错误。日期是根据格式化程序解析的,但日期如何表示解析后的值以及之后如何选择显示它们不再与格式化程序有任何联系。

恢复格式的唯一方法是再次写入parsedDate.format(formatter),然后您就回到了开始的位置,这就是formattedDate 已经存在的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多