Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

LocalDate – Create Date Object

1. The LocalDate

The LocalDate class in java represents the date object. It does not include time information in it. The sole purpose of this class is to represent only the date. In this short example, we will see how to create the data object.

2. LocalDate.of Method

LocalDate.of() is a static method which takes three parameters. The parameters are:

  1. Year: Represents the Year in integer format
  2. Month: Can be represented as integer 1-12 or Enum JANUARY to DECEMBER
  3. Day: It is again an integer representing the Day of the month.

Now let us look at the example to see how to create date objects in Java.

3. Constructing Date

Now have a look at the below code snippet:

Fig 1. Constructing the Date Object
Fig 1. Constructing the Date Object via LocalDate

Code Explanation

  1. First, we declared two variables of type LocalDate.
  2. In this snippet, we use first version of the method which takes month as integer. Here, we passed o5 as the second parameter which denotes the month. We constructed the date for 31 May 2001.
  3. The second version of the method takes month from the Enumeration which adds more readability to the code. In this code snippet, we constructed the date for 32 Mar 2017.

Now, we have two date objects in hand. Let us see how to print them.

4. Displaying Date

We can append the date object with a string, and it will be converted into string format. In the below code, we appended both the date objects with a string and printed that in the console output window. The screenshot below shows the output as well.

Fig 2. Printing the Date Object
Fig 2. Printing the LocalDate Object

5. Code Reference

Categories: Java

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.