Unable to Convert String to localDate with custom pattern [duplicate]

喜你入骨 提交于 2020-06-29 04:42:55

问题


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());

    }  
 }  

Apologizes for my explanation early days with java. Basically i am trying to convert input string "2020-06-14" into a localDate with a custom pattern "dd.MM.yyyy" in the end trying to have a date object not a String. Is there an other way to achieve it.


回答1:


A date has no format. Therefore when you write

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

your expectation is simply wrong. The date is parsed according to the formatter but how the date represents the parsed values and how it chooses to display them afterwards no longer has any connection to the formatter.

The only way to get your format back is to write parsedDate.format(formatter) once again and you are back where you started, which is what formattedDate was already.



来源:https://stackoverflow.com/questions/62372392/unable-to-convert-string-to-localdate-with-custom-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!