Home >Java >javaTutorial >Java program to display current date and time

Java program to display current date and time

WBOY
WBOYforward
2023-09-14 22:41:071223browse

Java program to display current date and time

In this article, we will learn how to display the current date and time. Java does not have a built-in Date class, but we can import the java.time package to use the date and time API. This package contains many date and time classes.

Below is a demonstration of the same -

Assume our input is -

Run the program

The desired output is -

The current date and time is: 2022/03/17 23:43:17

Algorithm

Step 1 - START
Step 2 - Declare an object of LocalDateTime namely date.
Step 3 - Define the values.
Step 4 - Define a date time format using DateTimeFormatter objects
Step 5 - Display the date and time using a specific formats
Step 6 - Stop

Example 1

Here, we bind all operations to the "main" function.

import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class Demo {
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      System.out.println("A LocalDateTime object has been defined");
      DateTimeFormatter date_time = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
      LocalDateTime now = LocalDateTime.now();
      System.out.println("\nThe current date and time is: " +date_time.format(now));
   }
}

Output

The required packages have been imported
A LocalDateTime object has been defined

The current date and time is: 2022/03/17 23:43:17

Example 2

Here, we encapsulate operations into functions that demonstrate object-oriented programming.

import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class Demo {
   static void Date_time(DateTimeFormatter date_time){
      LocalDateTime now = LocalDateTime.now();
      System.out.println("\nThe current date and time is: " +date_time.format(now));
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      System.out.println("A LocalDateTime object has been defined");
      DateTimeFormatter date_time = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
      Date_time(date_time);
   }
}

Output

The required packages have been imported
A LocalDateTime object has been defined

The current date and time is: 2022/03/29 08:55:28

The above is the detailed content of Java program to display current date and time. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete