简体   繁体   中英

Convert String to date in to yyyy-MM-dd for jUnit test

I am doing junit test for a method in the dao layer which requires to pass date value in the format to use in the SQL query. I have the date string "2006-08-14" and tried to convert into date using the following code.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date2 = sdf.parse("2006-08-14");
...
projectSchedule.setDate(date2);

The above code sets the value as

 Mon Aug 14 00:00:00 GST 2006

This fails in the DAO layer because the query expects the date in the format yyyy-MM-dd

select * from projects_bidders pb, projects_bidders_type pbt  where   cde_project = :projectId and cde_phase = :phaseId and  phase_start_date =  :phaseDate and foreign_id is not null and id_bidder = cde_bidder

query.setParameter("phaseDate", projectSchedule.getDate());

I referred many questions in in SO and didn't find any thing suitable.

I don't have control on DAO layer.

Date objects don't have a format. When you parse any object into a call to System.out.println() that objects' toString() method is called. Date 's toString() method always returns a String in that format.

For functionality like you describe you would have to subclass Date and override toString() like so;

class FormattedDate extends Date {

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

}

Your DOA, would of course need knowledge of the new FormattedDate class.


Edit Following Question Update;

Given that you have no control of the DOA or the SQL database software directly there is no way of changing the format the database software displays the date in. The datebase simply takes a Date object, which is a representation of the number of miliseconds since 0 am January 1st 1970 . The database software specifies how the dates are formatted, which you can not change except by changing the database access software's settings.

If you need to then fetch the date and display it in your own software, you will need to reformat it on your end because the data in the database probably doesn't have a format. A date's format, and data representing a date are entirely different constructs. Dates and Formats are entirely seperate, even in the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM