anand
anand

Reputation: 1751

How to Get java.sql.Date in particular Format only

Got one problem wherein i have to convert one date format to another date format and have to return java.sql.Date in a particular format.

I have input format as MM/dd/yyyy and output format should be dd-MM-yy ..but unable to get it

    DateFormat orgFormat = new SimpleDateFormat("MM/dd/yyyy");
    DateFormat targetFormat = new SimpleDateFormat("dd-MM-yy");
    
    try {
        java.util.Date inputDate = orgFormat.parse("01/01/2020");
        String formattedDate = targetFormat.format(inputDate);
        java.util.Date outputDate = targetFormat.parse(formattedDate);
        
        java.sql.Date sqlDate = new Date(outputDate.getTime());
        
        System.out.println(" Sql Date "+sqlDate);
        
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

OutPut: Sql Date 2020-01-01 // we need it as 01-01-20

Upvotes: 0

Views: 59

Answers (2)

Egan Wolf
Egan Wolf

Reputation: 3573

What System.out.println(" Sql Date "+sqlDate); does is calling toString() on sqlDate and if you check it's implementation you will see it returns the date in yyyy-MM-dd format. You can override toString method or use formatter when displaying the date

System.out.println(" Sql Date " + targetFormat.format(sqlDate));`

Upvotes: 1

ZIHAO LIU
ZIHAO LIU

Reputation: 387

Sql Date only save the timestamp, and the timestamp of 2020-01-01 is same as 01-01-20.

If you only want print as 01-01-20 , modify your sout as

System.out.println(" Sql Date "+ targetFormat.format(sqlDate));

If you really need a class, you can try write a class whitch extends java.sql.Date and override toString method.

For instance,

public class DateV2 extends java.sql.Date {
    public DateV2(int year, int month, int day) {
        super(year, month, day);
    }

    @Override
    public String toString() {
        DateFormat targetFormat = new SimpleDateFormat("dd-MM-yy");
        return targetFormat.format(this);
    }
}

and use DateV2 to replace java.sql.Date in your code.

Upvotes: 1

Related Questions