I'm trying to do something really simple, but starting to realize that dates in Java are a bit of minefield. All I want is to get passed groups of three ints ( a year, a month and a date) create some Date
objects, do some simple test on them (along the lines of as date A before date B and after January 1 1990), convert them to java.sql.Date
objects and pass them off to the database via JDBC.
All very simple and works fine using the java.util.Date(int year,int month,int day)
constructor. Of course that constructor is depreciated, and I'd like to avoid using depreciated calls in new code I'm writing. However all the other options to solve this simple problem seem stupidly complicated. Is there really no simple way to do what I want without using depreciated constructors?
I know the standard answer to all Java date related questions is "use joda time", but I really don't want to start pulling in third party libraries for such a seemingly trivial problem.
The standard alternate is using the Calendar Object. Calendar has one dangerous point (for the unwary) and that is the after / before methods. They take an Object but will only handle Calendar Objects correctly. Be sure to read the Javadoc for these methods closely before using them.
// Setting the pattern SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy"); // myDate is the java. util. Date in yyyy-mm-dd format // Converting it into String using formatter String strDate = sm. format(myDate); //Converting the String back to java.
You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.
The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you're using the default formatter.
The idea is to use the Calendar
class, like so:
Calendar cal = Calendar.getInstance(); cal.set(year, month, date); Date date = cal.getTime();
Indeed, if you check the Javadoc of the constructor you are mentioning, it is exactly what is suggested:
Date(int year, int month, int date) Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Or ... use JodaTime :-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With