Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String Date to String date different format [duplicate]

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);
}
like image 410
Murugesapillai Nagkeeran Avatar asked Feb 21 '13 10:02

Murugesapillai Nagkeeran


People also ask

How do I change one date format to another Date in python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.


2 Answers

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));
like image 84
asifsid88 Avatar answered Sep 23 '22 19:09

asifsid88


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);
}
like image 35
Tim Bender Avatar answered Sep 26 '22 19:09

Tim Bender