Bhuvan
Bhuvan

Reputation: 2229

Convert String Date in one format to Date object in another format

I have an input date as string in format dd/MM/yyyy

Now I want to convert it into Date object having format yyyy-MM-dd

Currently I am doing

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
Date dateObject = null;
  try {
    String date2 = formatter2.format(formatter.parse(date));
    dateObject = formatter2.parse(date2);
  }

input is: "04/02/2013"

But my date object is coming out to be --> Mon Feb 04 00:00:00 IST 2013

Desired output is : 2013-02-04 (Not in string but as a date object)

Upvotes: 0

Views: 6056

Answers (5)

Panadol Chong
Panadol Chong

Reputation: 1903

This work for me :

public Timestamp convertStringToTimeStamp(String dateinString){
        final String OLD_FORMAT = "dd/mm/yyyy";
        final String NEW_FORMAT = "yyyy-mm-dd";

        String newDateString;

        SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
        Date d = null;
        try {
            d = sdf.parse(dateinString);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        sdf.applyPattern(NEW_FORMAT);
        newDateString = sdf.format(d);

        return Timestamp.valueOf(newDateString+ " 00:00:00.00");
    }

Upvotes: 0

NilsH
NilsH

Reputation: 13821

A date has no specific output format. When you parse your first date, that's the date. Just store it, and when you need to output it to your desired format, use the second SimpleDateFormat.

Edit:

By "store it", i mean keep a reference to it until you need it represented in your desired String format.

Upvotes: 3

Miguel Rodrigues
Miguel Rodrigues

Reputation: 927

Your Date object is correct. Date contains information about the date.

You already have the string with the date with your desired mask:

String date2 = formatter2.format(formatter.parse(date));

try:

System.out.println(date2);

Upvotes: 0

BigMike
BigMike

Reputation: 6863

I think you're posing the wrong question here. As stated in comments you need this string formatting for querying the database, so, since JDBC works with java.sql.Date objects, be strict to it and convert your java.util.Date object to the JDBC managed type and use it directly (without worrying about formatting).

Try something like this:

String stmt = "select field from table where dateColumn = ?";
PreparedStatement st = connection.prepareStatement(stmt);
st.setDate(1, new java.sql.Date (yourJavaUtilDateObj);
ResultSet rs = st.executeQuery();

Should work on every JDBC driver out there.

Upvotes: 1

Rahul
Rahul

Reputation: 45060

You've already got your formatted date in date2. You needn't parse that again.

String date2 = formatter2.format(formatter.parse(date));
//dateObject = formatter2.parse(date2); // Not needed

System.out.println(date2);

Upvotes: 1

Related Questions