Creating a Specific Date

suggest change

While the Java Date class has several constructors, most are deprecated. The only acceptable ways to create a Date directly are the empty constructor and the constructor that takes a long (milliseconds since the epoch). Neither is handy unless you want the current instant or already have the epoch millis.

To create a new date, you will need a Calendar instance. From there you can set the Calendar instance to the date that you need.

Calendar c = Calendar.getInstance();

This returns a new Calendar set to the current time. Calendar has many methods for changing its date and time or setting it outright. In this case, we set a specific date.

c.set(1974, 6, 2, 8, 0, 0);
Date d = c.getTime();

The getTime method returns the Date we need. The Calendar set methods set only the fields you pass. If you set the year alone, the other fields stay unchanged. Months are zero-based, so 6 is July (Calendar.JULY), not June.

PITFALL

In many cases, this code snippet fulfills its purpose, but keep in mind that two important parts of the date/time are not defined.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents