w3resource

Java: Print current date and time in the specified format


15. Print Current Date and Time

Write a Java program to print the current date and time in the specified format.

Visual Presentation:

Java String Exercises: Print current date and time in the specified format


Sample Solution:

Java Code:

// Import the Calendar class from the java.util package.
import java.util.Calendar;

// Define a public class named Exercise15.
public class Exercise15 {
    // Define the main method.
    public static void main(String[] args) {
        // Get an instance of the Calendar class representing the current date and time.
        Calendar c = Calendar.getInstance();
        
        // Print the message indicating current date and time.
        System.out.println("Current Date and Time :");

        // Print the formatted date (month day, year) using the specified format.
        System.out.format("%tB %te, %tY%n", c, c, c);
        
        // Print the formatted time (hour:minute am/pm) using the specified format.
        System.out.format("%tl:%tM %tp%n", c, c, c); 
    }
}

Sample Output:

Current Date and Time :                                                                                       
June 19, 2017                                                                                                 
3:13 pm 

N.B. : The current date and time will change according to your system date and time.

Flowchart:

Flowchart: Java String Exercises - Print current date and time in the specified format


For more Practice: Solve these Related Problems:

  • Write a Java program to display the current date and time in multiple time zones.
  • Write a Java program to format the current date and time in a custom pattern using SimpleDateFormat.
  • Write a Java program to print the current date and time along with the day of the week.
  • Write a Java program to display the current date and time and then calculate the date 100 days later.

Go to:


PREV : Equals Ignore Case.
NEXT : Get Byte Array from String.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.