Creating a Specific Date

suggest change

While the Java Date class has several constructors, you’ll notice that most are deprecated. The only acceptable way of creating a Date instance directly is either by using the empty constructor or passing in a long (number of milliseconds since standard base time). Neither are handy unless you’re looking for the current date or have another Date instance already in hand.

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 instance set to the current time. Calendar has many methods for mutating it’s date and time or setting it outright. In this case, we’ll set it to a specific date.

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

The getTime method returns the Date instance that we need. Keep in mind that the Calendar set methods only set one or more fields, they do not set them all. That is, if you set the year, the other fields remain unchanged.

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