Java Program For Date And Time
Chapter:
Miscellaneous
Last Updated:
24-03-2023 14:32:25 UTC
Program:
/* ............... START ............... */
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println("Current date and time: " + formattedDateTime);
}
}
/* ............... END ............... */
Output
Current date and time: 24-03-2023 11:25:30
Notes:
-
The Java program provided above is a simple example of how to display the current date and time in a specific format.
- We first import two classes, LocalDateTime and DateTimeFormatter, from the java.time package. These classes provide the functionality we need to work with dates and times in Java.
- We then create a new class called DateTimeExample that contains a main method, which is the entry point for the program.
- Inside the main method, we create a LocalDateTime object called now using the now() method. This object represents the current date and time.
- We then create a DateTimeFormatter object called formatter using the ofPattern() method. This object specifies the format we want to use to display the date and time. In this case, the format is "dd-MM-yyyy HH:mm:ss", which means we want to display the day, month, year, hours, minutes, and seconds of the date and time.
- Next, we use the format() method of the now object to format the date and time using the formatter object. This returns a String object representing the formatted date and time.
- Finally, we print out the formatted date and time using the System.out.println() method. This displays the date and time on the console in the format we specified earlier.
- So in summary, the program gets the current date and time, formats it in a specific way using a DateTimeFormatter object, and then prints out the formatted date and time using System.out.println().
Tags
#Java Program For Date And Time # Date Java example, #Java Date, #Time in Java, #Java get current date