2

I have a DATE datatype mysql column in a table. I want to set the value of that column from my java code in the format YYYY-MM-DD

I used following code to test these formats..

Calendar c = Calendar.getInstance();
c.setTime(new Date());
String d = c.YEAR+ "-"+c.MONTH+"-"+c.DATE;

But I get some wierd output if i print out that value in console. Please help. How else can I accomplish this ?

Anand
  • 10,310
  • 24
  • 90
  • 135

2 Answers2

4

In JDBC you can use the setDate() method to set DATE value in the prepared statement, see the API of PreparedStatement. This converts the value to the DATE type in the database.

PreparedStatement prep = con.prepareStatement("some query with a DATE field");
Date d = new Date(System.currentTimeMillis());
// just an example (its the java.sql.Date class, not java.util.Date)
prep.setDate(index, d);
// ...

To get this java.sql.Date object back with the value of the DATE field use the getDate() method of the ResultSet class.

ResultSet res = con.executeQuery("some query with a DATE field");
Date d = res.getDate(index);

You can work with the d object like a java.util.Date object (like using in a Calendar object) as it extends from it.

Progman
  • 16,827
  • 6
  • 33
  • 48
2

What you have to do is:

String d = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DATE)

If I remember correctly you also have to add +1 to the month as it returns offset (counted from 0) instead of just month value (which is stupid for me, but I didn't do the design).

Also, you might like to check SimpleDateFormat and its capabilities to format a date in nice way.

pajton
  • 15,828
  • 8
  • 54
  • 65