Converting from Date ojbect to Date object

I have a requirement. I want to convert a Date object to a formatted Date object.

I mean,

`Date d = new Date();System.out.println(d);' 

      

Result: Thu Apr 05 11:28:32 GMT + 05: 30 2012

I want the output to be like 05 / APR / 2012 . And the output object must be Date, not String. If you don't understand at all, I will post more clearly

Thank.

+3


source to share


3 answers


You don't need third party APIs, just use DateFormat to parse / format dates by providing a date format template. Example code:

Date date = new Date();
DateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
String formattedDate = df.format(date);

System.out.println(formattedDate.toUpperCase());

      



Demo version is here.

+7


source


Before answering, I'll let others understand that the OP is actually using POJOs to represent database objects, one of his POJOs contains a Date Type field. And it wants the date to be in oracle format, but it remains a Date object. (From OP's comment here )

You just need to extend the Date

class and overridepublic String toString();

public class MyDate extends Date
{
    @Override
    public String toString()
    {
        DateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
        String formattedDate = df.format(this);
        return formattedDate;
    }
}

      

And then, in your POJO, where you initialize your Date object:



Date databaseDate=new MyDate();
// initialize date to required value.

      

Now databaseDate is a Date object, but it will provide the required format wherever needed.

EDIT: Database has nothing to do with programming language data types. When POJOs are inserted into the database, all their values ​​are converted to strings. And how the object is converted to a string is defined in the toString method of that class.

+1


source


I think he wants to use Date in System.out.println (), so we can try extending the Date class and overriding toString ().

Here is the code:

import java.util.Date;


 class date extends Date {

    int mm,dd,yy;
    date()
    {

        Date d = new Date();
        System.out.println(d);
        mm=d.getMonth();
        dd=d.getDate();
        yy=d.getYear();

    }

    public String toString()
    {  Integer m2=new Integer(mm);
    Integer m3=new Integer(dd);
    Integer m4=new Integer(yy);
        String s=m2.toString() + "/"+ m3.toString() + "/" + m4.toString();

        return s;
    }


}

public class mai
{
public static void main(String... args)
{

    date d=new date();
    System.out.println(d);

}

}

      

0


source







All Articles