如何创建具有特定格式的Date对象

时间:2014-08-23 10:29:56

标签: java date java.util.date

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

2 个答案:

答案 0 :(得分: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");

    /*
     * additional constructors
     */

    @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 = (MyDate) df.parse(testDateString);
System.out.println(d1);

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

答案 1 :(得分:0)

试试这样:

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

希望这可以帮到你!

相关问题