Set a date object in java from a string retaining the same format

1.1k Views Asked by At

I have an application where the data is read from the database. Database has a date column value stored in the format

Sat Oct 19 10:03:00 EDT 2013

Then I read database from my java code using getters and setters where the date column is

node.setHeadTime(Date newDate)
node.getHeadTime();

Hence Its a date object I get the date as

Sat Oct 19 19:33:00 IST 2013

Now I do some processing wherein I need to update the data and store it back to the database.

The data is changed to

Sat Oct 19 19:35:00 IST 2013

I need to store back this data to the database as

Sat Oct 19 10:05:00 EDT 2013

I tried the following code:

DateFormat edtFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
        TimeZone edt = TimeZone.getTimeZone("America/New_York");
        edtFormat.setTimeZone(edt);
        DateFormat df = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy"); // The timezone 'z' identifier was missing, I have added that now.
        Date dd1 = df.parse(headDate); //headdate is the date having string Sat Oct 19 19:35:00 IST 2013

String hd=edtFormat.format(dd1);
log.info("date "+hd);
        fnFillDetails(String hd);

this prints Sat Oct 19 10:05:00 EDT 2013 successfully.

But my issue is After I change the format I am sending it to a function

fnFillDetails(String hd){

node.setheaddate(hd); // But this obviously has an error as type mismatch of Date and String. 
}

I tried all possible workarounds none worked. I cannot change the datatype of the headdate to String.

How do I fix this issue? I need to retain the format and change it back to orignal format in the database.

1

There are 1 best solutions below

0
On
        String headDate = "Sat Oct 19 19:35:00 IST 2013";

        DateFormat edtFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
        TimeZone edt = TimeZone.getTimeZone("America/New_York");
        edtFormat.setTimeZone(edt);

        DateFormat istFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
        TimeZone ist = TimeZone.getTimeZone("Asia/Kolkata");
        istFormat.setTimeZone(ist);

        Date dd1 = istFormat.parse(headDate);
        String hd=edtFormat.format(dd1);
        System.out.println(hd);

So now if you want to pass edt format to fnFillDetails then call

Date edtDate = edtFormat.parse(hd);
fnFillDetails(edtDate);