Java Program to print current date-time.
Objective
Write a Java program to print the current system date and time.
Algorithm / Approach
- Import
java.util.Date. - Instantiate a new Date object:
Date d = new Date();. - The constructor automatically captures the exact millisecond it was created.
- Call
d.toString()(or just print the object directly) to see the default formatted time.
DateDemo.java
import java.util.*;
public class DateDemo {
public static void main(String[] ar) {
//Instantiate a Date object
Date d = new Date();
//display time & date using toString()
System.out.println(d.toString());
}
}
Expected Output
Fri Dec 27 21:51:14 IST 2013
Explanation of the Program
- The
java.util.Dateclass represents a specific instant in time, with millisecond precision. - When instantiated with an empty constructor, it queries the operating system for the current time.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)