3

The deprecated java.sql.Date constructor was far more intuitive - Date(int year, int month, int day). But now we are required to use new java.sql.Date(long date).

I can't find on the documentation on how to write an actual long date myself. Is there any other approach to constructing an sql date in java besides using java.util.Date().getTime()?

Mairbek Khadikov
  • 7,939
  • 3
  • 35
  • 51
harryo
  • 483
  • 1
  • 8
  • 14

3 Answers3

3

The reason that Date(year, month, day) is deprecated is because it's locale ignorant. If you want to just use the standard java classes, the standard way is to Calendar.getInstance, and then set the year, month and day using the .set methods of the resulting Calendar. However, as I've learned in 3 years of StackOverflow, the better way is to use Joda.

Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
  • An alternative is to use a DateFormat to parse a String to a Date, and call getTime(). – JB Nizet Jan 22 '12 at 22:11
  • Okay, I've downloaded the jar for Joda Time. Based looking up some guides on Joda time and sql, such as here http://stackoverflow.com/questions/1071800/how-to-use-jodatime-with-java-sql-timestamp , I understand how using the constructor works. – harryo Jan 22 '12 at 22:13
  • But the example in the link only provides conversion from JodaTime to timestamp. What if I want to convert JodaTime to java.sql.Date in order to insert it into my database through a java class? – harryo Jan 22 '12 at 22:14
1

Here is a quick and easy way to create a java.sql.Date from year, month, and day. It formats a date string and uses Date.valueOf(String).

/** 
* Create a java.sql.Date from from year, month, and day of the month.
*/
private java.sql.Date createSqlDate(int year, int month, int day) {

    // Create a date string with leading zeros for month and day.
    String dateString = String.format("%d-%02d-%02d", year, month, day);

    return java.sql.Date.valueOf(dateString);
}
stackoverflowuser2010
  • 38,621
  • 48
  • 169
  • 217
0

I think jdk alternative to the (year, month, day) constructor would be using the Calendar class which is a bit more cumbersome since you have to set the fields independently.

However, as Paul mentioned, using Joda Time is a great alternative if you can add the jar to your project.