How to Create a Specific Date in Java

Creating a Specific Date

While the Java Date and Time class have 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.

  • the (1974, 6, 2, 8, 0, 0) parameters are interpreted within the default timezone, defined somewhere else,
  • the milliseconds are not set to zero, but filled from the system clock at the time the Calendar instance is created.

Converting Date to a certain String format

format() from SimpleDateFormat class helps to convert a Date object into certain format String object by using the supplied pattern string.

Date today = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy"); //pattern is specified here
System.out.println(dateFormat.format(today)); //25-Feb-16
Patterns can be applied again by using applyPattern()
dateFormat.applyPattern("dd-MM-yyyy");
System.out.println(dateFormat.format(today)); //25-02-2016
dateFormat.applyPattern("dd-MM-yyyy HH:mm:ss E");
System.out.println(dateFormat.format(today)); //25-02-2016 06:14:33 Thu

Note: Here mm (small letter m) denotes minutes and MM (capital M) denotes month. Pay careful attention when formatting years: capital “Y” (Y) indicates the “week in the year” while lower-case “y” (y) indicates the year.

LocalTime

To use just the time part of a Date use LocalTime. You can instantiate a LocalTime object in a couple ways

  1. LocalTime time = LocalTime.now();
  2. time = LocalTime.MIDNIGHT;
  3. time = LocalTime.NOON;
  4. time = LocalTime.of(12, 12, 45);

LocalTime also has a built-in toString method that displays the format very nicely.

System.out.println(time);

you can also get, add and subtract hours, minutes, seconds, and nanoseconds from the LocalTime object i.e.

time.plusMinutes(1);
time.getMinutes();
time.minusMinutes(1);

You can turn it into a Date object with the following code:

LocalTime lTime = LocalTime.now();
Instant instant = lTime.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);

this class works very nicely within a timer class to simulate an alarm clock.

Convert formatted string representation of date to Date object

This method can be used to convert a formatted string representation of a date into a Date object.

/**
*  Parses the date using the given format.
*  @param formattedDate the formatted date string
*  @param dateFormat the date format which was used to create the string.
*  @return the date
*/
public static Date parseDate(String formattedDate, String dateFormat) {
    Date date = null;
    SimpleDateFormat objDf = new SimpleDateFormat(dateFormat);
    try {
      date = objDf.parse(formattedDate);
      } catch (ParseException e) {
      // Do what ever needs to be done with exception.
    }
    return date;
}
Creating Date objects
Date date = new Date();
System.out.println(date); // Thu Feb 25 05:03:59 IST 2016

Here this Date object contains the current date and time when this object was created.

Calendar calendar = Calendar.getInstance();
calendar.set(90, Calendar.DECEMBER, 11);
Date myBirthDate = calendar.getTime();
System.out.println(myBirthDate); // Mon Dec 31 00:00:00 IST 1990

Date objects are best created through a Calendar instance since the use of the data constructors is deprecated and discouraged. To do se we need to get an instance of the Calendar class from the factory method. Then we can set year, month and day of month by using numbers or in case of months constants provided py the Calendar class to improve readability and reduce errors.

calendar.set(90, Calendar.DECEMBER, 11, 8, 32, 35);
Date myBirthDatenTime = calendar.getTime();
System.out.println(myBirthDatenTime); // Mon Dec 31 08:32:35 IST 1990

Along with date, we can also pass time in the order of an hour, minutes, and seconds.

Leave a Comment