Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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").

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
118 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...