Question

I am new to Java. Postgres db contain date format is yyyy-MM-dd. I need to convert to dd-MM-yyyy.

I have tried this, but wrong result is display

   public static void main(String[] args) throws ParseException {

    String strDate = "2013-02-21";
      DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      Date da = (Date)formatter.parse(strDate);
      System.out.println("==Date is ==" + da);
      String strDateTime = formatter.format(da);

      System.out.println("==String date is : " + strDateTime);
}
Was it helpful?

Solution

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("2013-02-21");
System.out.println(format2.format(date));

OTHER TIPS

You need to use two DateFormat instances. One which contains the format of the input string and a second one which contains the desired format for the output string.

public static void main(String[] args) throws ParseException {

    String strDate = "2013-02-21";

    DateFormat inputFormatter = new SimpleDateFormat("yyyy-MM-dd");
    Date da = (Date)inputFormatter.parse(strDate);
    System.out.println("==Date is ==" + da);

    DateFormat outputFormatter = new SimpleDateFormat("dd-MM-yyyy");
    String strDateTime = outputFormatter.format(da);
    System.out.println("==String date is : " + strDateTime);
}

Reference these formats Java Date Format Docs:

Formats for datetime

Try this Code:

String myDate= "2013-02-21";
DateFormat iFormatter = new SimpleDateFormat("yyyy-MM-dd");
DateFormat oFormatter = new SimpleDateFormat("dd-MM-yyyy");
String strDateTime = oFormatter.format(iFormatter.parse(myDate));

You need a format to parse the current state and a format to generate the desired output.

String strDate  = "2013-02-21";
DateFormat to   = new SimpleDateFormat("dd-MM-yyyy"); // wanted format
DateFormat from = new SimpleDateFormat("yyyy-MM-dd"); // current format
System.out.println(to.format(from.parse(strDate)));

Try following utility function.

// convert String date to another string date
public String convertStringDateToAnotherStringDate(String stringdate, String stringdateformat, String returndateformat){        

        try {
            Date date = new SimpleDateFormat(stringdateformat).parse(stringdate);
            String returndate = new SimpleDateFormat(returndateformat).format(date);
            return returndate;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }

}

// call function with required parameter arguments
String resultDate = convertStringDateToAnotherStringDate("2017-06-22", "yyyy-MM-dd", "dd-MM-yyyy")
System.out.println(resultDate);

Result: 22-06-2017

you are using the same formater to handle different formats.

you need to provide two formatters new SimpleDateFormat("dd-MM-yyyy"); for converting 2013-02-21 to date object and new SimpleDateFormat("dd-MM-yyyy"); for formating the date object to the string 21-02-2013.

First, you shouldn’t get your date as a String from your Postgres database. You should get it as an object of a type representing a date.

Second, while in 2013 use of Date and SimpleDateFormat were commonplace and reasonable, days have gone by and new and better date and time classes have come out and have come into common use. IMHO no one should use the old classes anymore and I consider them long outdated.

To get a LocalDate object from your ResultSet from your database:

    LocalDate da = yourResultSet.getObject(3, LocalDate.class);

(I am assuming the date is in column 3 in the query).

To format it into dd-MM-yyyy:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
    String strDateTime = da.format(formatter);
    System.out.println("==String date is : " + strDateTime);

This would give output like

==String date is : 21-02-2013

Finally, in case you have got a string like in the question and want to reformat it into your desired format:

    String strDate = "2013-02-21";      
    LocalDate da = LocalDate.parse(strDate);
    System.out.println("==Date is ==" + da);

This prints

==Date is ==2013-02-21

I am taking advantage of the fact that the string matches the ISO 8601 standard date format that is the default for the modern date and time classes. So in this case we don’t need an explicit formatter for parsing, as we would for parsing other formats.

Formatting into your desired format happens precisely as before.

An example of the trouble with the old classes

On my computer the output from the code in the question is

==Date is ==Tue Aug 06 00:00:00 CET 26
==String date is : 06-08-0026

You are clearly getting a wrong result, and you are getting no clue what was wrong. What was wrong was that you were parsing your db date string, 2013-02-21, with the formatter you intended for the new string, dd-MM-yyyy. So it is parsed as the 2013th February 21 AD. There aren’t 2013 days in february? No problem to a SimpleDateFormat with default settings, it just continues counting days into the following months and years and ends up at August 6 five and a half years later, but still very early in history.

If we try doing similarly with the modern classes:

    LocalDate.parse(strDate, formatter);

— we get java.time.format.DateTimeParseException: Text '2013-02-21' could not be parsed at index 2. This is because the formatter indicated 2-digit day, so when after parsing two digits there are more digits in the input string, it’s an error and is reported as such. I consider this behaviour more correct and more helpful.

You need to use SimpleDateFormat instance and pass the date pattern you prefer.

Current pattern: yyyy-MM-dd

The pattern that is needed: dd-MM-yyyy

Now try the following. It produces the required pattern of date format.

public class App {
    public static void main(String[] args) {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
        Date date = null;
        try {
            date = format1.parse("2013-02-21");
            System.out.println(format1.format(date)); //current format: 2013-02-21
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(format2.format(date)); //the format that is needed : 21-02-2013
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top