如何使用特定格式创建日期对象

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

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

输出的字符串:

02/04/2014

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


你想要什么样的输出?长整型数值吗? - vipul mittal
请描述您期望/想要获得的结果字符串。 - Or B
2个回答

5
如果您想要一个始终能按照您要求的格式打印的日期对象,您需要创建自己的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()将返回格式化后的日期字符串。

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

希望这能帮到您!

1
你的代码和OP发布的代码有什么区别? - Tom
你为什么要将 parse 的结果转换为 Date 类型?它本身就返回一个 Date 对象。 - Tom
我不想要这个输出:Wed Apr 02 00:00:00 GMT 2014。我需要的是02/04/2014。 - user2243468
@user2243468,如果您使用了您发布的代码,那么现在有一个问题吗?date2(或者您的d1)无法本地打印所需的格式?为此,您需要创建自己的类MyDate,该类将扩展Date类,然后您可以重写toString方法。在其中,您可以按照您想要的方式格式化输出。 - Tom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接