provokoe
provokoe

Reputation: 178

change date format to query database

how do I change date format of the following date

Thu May 17 00:00:00 GMT+05:30 2012

to

2012-05-17 00:00:00

I need it as date and not as string. I am using

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("")

But its not giving the result. Actually I am storing the values date wise. So when someone enters the data for the same date again it should overwrite. If I pass it as date object into the hibernate query it gives the result. But not always. ON few occasions it inserts again that is it inserts duplicate data for the same date. Befroe entering I am adding a method to check if data exists for that date. criteria.add(Restrictions.eq("date", date));

Upvotes: 0

Views: 1548

Answers (4)

lfergon
lfergon

Reputation: 973

String date = "Thu May 17 00:00:00 GMT+05:30 2012";
String oldFormat = "EEE MMM dd hh:mm:ss z yyyy";
String newFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);
sdf2.format(sdf1.parse(date))

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500515

You shouldn't be doing string manipulation at all here. You've said in comments that it's a date/time field in the database, so why would there be any string conversion involved in your code?

Specify parameters in JDBC as java.sql.Date, java.sql.Timestamp or whatever - and then fetch them that way too. Don't do a string conversion. Ignore whatever format happens to be displayed when you query the database in a tool - don't think of the result as having a "format" at all - they're just dates.

Upvotes: 1

Samir Mangroliya
Samir Mangroliya

Reputation: 40416

String str ="Thu May 17 00:00:00 GMT+05:30 2012";

        DateFormat old_format = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
        Date newDate = null;
        try {
            newDate = old_format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        DateFormat new_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = new_format.format(newDate);

        System.out.println("==>"+date);

Upvotes: 1

Ludwig Magnusson
Ludwig Magnusson

Reputation: 14389

Do exactly as you do now but change parse("") to format(theDate)

theDate being the Date object you want to format

See http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html#format(java.util.Date)

Upvotes: 0

Related Questions