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

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

输出字符串:

2014 年 2 月 4 日

现在我需要以d1相同方式格式化的日期(“02/04/2014”)。

4

2 回答 2

4

如果您想要一个始终打印所需格式的日期对象,您必须创建一个自己的类子类Date并在那里覆盖toString

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);
    }
}

现在您可以像以前一样创建此类,Date而无需SimpleDateFormat每次都创建。

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

输出是23/08/2014

这是您在问题中发布的更新代码:

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

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

请注意,您不必再调用df.format(d1)d1.toString()将日期作为格式化字符串返回。

于 2014-08-23T12:07:35.473 回答
2

试试这样:

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

希望这可以帮助你!

于 2014-08-23T10:36:01.417 回答