Java change date format from custom date to MM dd yyyy

24,925

Solution 1

In short, you're not using the right format for parsing. You need to use two DateFormat instances; one for parsing and one for formatting.

DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy");
Date convertedDate = parser.parse(datePlayed);
String output = formatter.format(convertedDate);

Solution 2

Date da = new Date();
SimpleDateFormat ft = new SimpleDateFormat("E, dd/MM/yyyy !");
System.out.println("Update : " + ft.format(da));

You can change your date style do you want at: E, dd/MM/yyyy !

Good luck !

Share:
24,925
user1070764
Author by

user1070764

Updated on July 09, 2022

Comments

  • user1070764
    user1070764 almost 2 years

    I am trying to convert a String value that is stored in a database,for example "2012-01-20", to be in the format January 20, 2012.

    I have seen some examples, but they are using Date which works with SimpleDateFormat.

    As an example here is one way I tried but the "try" always fails and the result is null

    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    Date convertedDate=null;
    
    try {
    
        convertedDate = df.parse(datePlayed);                   
    
    } catch(ParseException e){
        e.printStackTrace();
    }   
    
    • Sam Trost
      Sam Trost about 12 years
    • James Montagne
      James Montagne about 12 years
      If your dates look like 2012-01-20, why would you use the format MM/dd/yyyy in creating your SimpleDateFormat?
    • Matt Ball
      Matt Ball about 12 years
      @JamesMontagne I couldn't have said it better myself.
    • user1070764
      user1070764 about 12 years
      @JamesMontagne thats not what i actually used that was just the original example i found of one way to do it, your right tho i want month displayed, MMMM.
  • user1070764
    user1070764 about 12 years
    That worked! now i realize what i had to do with setting up the parser first to recognize my pattern. Thank you very much for the fast response
  • Matt Ball
    Matt Ball about 12 years
    Neither of these are the problem.
  • Thorn
    Thorn about 12 years
    Since we didn't see his actual input, we don't know for sure what the problem is. You an I offered solutions to the most likely causes of the problem.
  • Basil Bourque
    Basil Bourque over 10 years
    FYI, java.sql.Date is a subclass of java.util.Date. No need to convert.
  • Ashok kumar Ganesan
    Ashok kumar Ganesan over 3 years
    we can remove the second line and use the parser in 4th line to replace the formatter as parser to make it efficient right?