How can I create a Date object with a specific format

假如想象 提交于 2019-12-28 07:03:06

问题


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


回答1:


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

    /*
     * additional constructors
     */

    @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 = (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.




回答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!



来源:https://stackoverflow.com/questions/25460965/how-can-i-create-a-date-object-with-a-specific-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!