Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the accepted way to replace java.util.Date(year,month,day)

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.

like image 353
dagw Avatar asked Apr 21 '10 22:04

dagw


People also ask

What can I use instead of Java Util date?

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.

How do I change the date format in Java Util?

// 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.

How do I create a new Java Util date?

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.

What is the default format of Java Util date?

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.


1 Answers

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 :-).

like image 185
João Silva Avatar answered Oct 04 '22 11:10

João Silva