convert string into date format in java

前端 未结 3 1437
傲寒
傲寒 2021-01-24 16:50

I want to convert this string to the following date format.

  String s = \"2-26-2013\";
  Date date = new SimpleDateFormat(\"EEEE, MMMM/dd/yyyy\").parse(s);
  Sy         


        
相关标签:
3条回答
  • 2021-01-24 17:12

    Well yes. The argument you pass into the constructor of SimpleDateFormat says the format you expect the date to be in.

    "EEEE, MMMM/dd/yyyy" would be valid for input like "Tuesday, February/26/2013". It's not even slightly valid for "2-26-2013". You do understand that you're parsing the text at the moment, not formatting it?

    It looks like you want a format string of "M-dd-yyyy" or possibly "M-d-yyyy".

    If you're trying to convert from one format to another, you need to first specify the format to parse, and then specify the format to format with:

    SimpleDateFormat parser = new SimpleDateFormat("M-dd-yyyy");
    SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM/dd/yyyy");
    Date date = parser.parse(input);
    String output = formatter.format(date);
    
    0 讨论(0)
  • 2021-01-24 17:16
    Date date = new SimpleDateFormat("MM-dd-yyyy").parse(s);
    

    The argument to SimpleDateFormat defines the format your date it in. The above line matches your format, and works. Your example does not match.

    0 讨论(0)
  • 2021-01-24 17:28

    Instead of using MMMM/dd/yyyy you need to used MM-dd-yyyy. SimpleDateFormat expects the pattern to match what its trying to parse.

    0 讨论(0)
提交回复
热议问题