Java Program to Print Date and Time in a Specific Format

Learn how to print date and time in a specific format in Java using java.util.Date, SimpleDateFormat, and java.sql.Date. Display dates in different formats with examples.

Code Explanation (Step-by-Step)

  • Create a java.util.Date object and display the current day, date, time, and time zone.
  • Use the SimpleDateFormat class to format the date and time in a user-defined pattern.
  • Convert the Date object into a custom format such as yyyy-MM-dd HH:mm:ss.
  • Create a java.sql.Date object using the getTime() method and display only the date portion (year, month, and day).
				
					import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class DateUtilDemo {
    public static void main(String[] args) {

        java.util.Date ju = new java.util.Date();
        System.out.println("java.util.Date format :-- " + ju);

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Customized format :-- " + df.format(ju));

        java.sql.Date sd = new java.sql.Date(ju.getTime());
        System.out.println("SQL format :-- " + sd);
    }
}
				
			

Output :-
java.util.Date format :– Tue Aug 15 22:45:14 IST 2023
Customized format :– 2023-08-15 22:45:14
SQL format :– 2023-08-15

Format Date and Time Using SimpleDateFormat

				
					import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatDemo {

    public static void main(String[] args) {

        Date date = new Date();

        SimpleDateFormat sdf =
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String formattedDate = sdf.format(date);

        System.out.println("Current Date and Time: "
                + formattedDate);
    }
}
				
			

Output :-
Current Date and Time: 2026-08-16 22:30:45