Creating a Specific Date and Converting Date to String format


Creating a Specific Date


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(1947, 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 (1947, 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 currentDate = new Date();
 
SimpleDateFormat customDateFormat = new SimpleDateFormat("dd/MMM/yyyy");
System.out.println(customDateFormat.format(currentDate)); // Outputs something like: 30/Dec/2023

Patterns can be applied again by using applyPattern()

SimpleDateFormat customFormat = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(customFormat.format(currentDate)); // Outputs something like: 2023/12/30
 
customFormat.applyPattern("MM-dd-yyyy HH:mm:ss");
System.out.println(customFormat.format(currentDate)); // Outputs something like: 12-30-2023 14:55:30

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.

Basic Programs