3
String testDateString = "02/04/2014";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 

Date d1 = df.parse(testDateString);
String date = df.format(d1);

Output String:

02/04/2014

Now I need the Date d1 formatted in the same way ("02/04/2014").

Tom
  • 16,842
  • 17
  • 45
  • 54
user2243468
  • 119
  • 2
  • 9

2 Answers2

5

If you want a date object that will always print your desired format, you have to create an own subclass of class Date and override toString there.

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyDate extends Date {
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    public MyDate() { }

    public MyDate(Date source) {
        super(source.getTime());
    }

    // ...

    @Override
    public String toString() {
        return dateFormat.format(this);
    }
}

Now you can create this class like you did with Date before and you don't need to create the SimpleDateFormat every time.

public static void main(String[] args) {
    MyDate date = new MyDate();
    System.out.println(date);
}

The output is 23/08/2014.

This is the updated code you posted in your question:

String testDateString = "02/04/2014";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 

MyDate d1 = new MyDate(df.parse(testDateString));
System.out.println(d1);

Note that you don't have to call df.format(d1) anymore, d1.toString() will return the date as the formated string.

Tom
  • 16,842
  • 17
  • 45
  • 54
2

Try like this:

    SimpleDateFormat sdf =  new SimpleDateFormat("dd/MM/yyyy");

    Date d= new Date(); //Get system date

    //Convert Date object to string
    String strDate = sdf.format(d);

    //Convert a String to Date
    d  = sdf.parse("02/04/2014");

Hope this may help you!

Krupa Patel
  • 3,309
  • 3
  • 23
  • 28
  • 1
    Where is the difference between your code and the code posted by OP? – Tom Aug 23 '14 at 10:54
  • And why do you cast the result of `parse` to Date? It returns a Date object. – Tom Aug 23 '14 at 11:14
  • I dont want this Wed Apr 02 00:00:00 GMT 2014 output. I need 02/04/2014 – user2243468 Aug 23 '14 at 11:47
  • @user2243468 and you get this using your code you've posted. There is the problem now? That `date2` (or your `d1`) won't print your desired format natively? For that you have to create your own class `MyDate` that will extend the `Date` class and there you override the `toString` method. In there you can format your output how you want. – Tom Aug 23 '14 at 11:54