Date and Time is one of the important topic in any programming language. In Java we can import the module named Java.time.LocalDateTime from Java to work with Date and Time.
Let us start with the below example.
import java.time.LocalDateTime; class MyApplication { public static void main(String[] arg) { LocalDateTime x = LocalDateTime.now(); System.out.println("Current Date and Time is: "+x); } }
Now, if we dissect the output,
So, with the below statement,
LocalDateTime x = LocalDateTime.now();
We get an object, x that has Year, Month, Day, Hour, Minute and Second.
To use LocalDateTime we need to import the java.time.LocalDateTime class,
import java.time.LocalDateTime;
Now, let us see how to work with Date and Time separately.
To get the date only. Let us look at the below example.
import java.time.LocalDate; class MyApplication { public static void main(String[] arg) { LocalDate x = LocalDate.now(); System.out.println("Today's Date is : "+x); } }
So, with the below statement,
LocalDate x = LocalDate.now();
We get an object, x that has the date only i.e. Year, Month, Day.
Similarly, to use LocalDate we need to import the java.time.LocalDate class,
import java.time.LocalDate;
And if you see the output.
Today's date is 2023-02-15
To get the time only. Let us look at the below example.
import java.time.LocalTime; class MyApplication { public static void main(String[] arg) { LocalTime x = LocalTime.now(); System.out.println("Current Time is : "+x); } }
And if you see the above output, current time is displayed as output in the below format.
Now, let us say we need the date and time in a particular format.
Say we want a date in the below format,
15-Feb-2023
And that's exactly what we are going to see next,
As said above let us display date in the below format,
15-Feb-2023
Let us see in the below example,
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; class MyApplication { public static void main(String[] arg) { LocalDateTime x = LocalDateTime.now(); DateTimeFormatter y = DateTimeFormatter.ofPattern("dd-MMM-yyyy"); String myDate = x.format(y); System.out.println("Current date is : "+myDate); } }
And as said, we have displayed the date in the below format,
15-Feb-2023
And to achieve that we have followed the three step process :
LocalDateTime x = LocalDateTime.now();
DateTimeFormatter y = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String myDate = x.format(y);
And if we see the output, we got the date displayed in our desired format.