Java provides a built-in Date class available in the java.util package. This class encapsulates the current date and time.
The Date class supports two constructors as shown in the table below:
| Nº | Constructor | Description |
|---|---|---|
| 1 | Date() | This constructor initializes the object with the current date and time. |
| 2 | Date(long millisec) | This constructor accepts an argument that represents the number of milliseconds that have passed since midnight, January 1, 1970. |
Current Date and Time
This is the simplest method to get the current date and time in Java. You can use a basic Date object with the toString() method to display the current date and time as shown below:
Source Code:
import java.util.Date;
public class DateTime {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date.toString());
}
}Result:
Date Formatting Using SimpleDateFormat
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing a user-defined pattern for formatting dates.
SimpleDateFormat Format Codes
To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern characters which are defined as follows:
| Character | Description | Example |
|---|---|---|
| G | Era designator | AD |
| y | Year in four digits | 2001 |
| M | Month in year | July or 07 |
| d | Day in month | 10 |
| h | Hour in A.M/P.M (1~12) | 12 |
| H | Hour in day (0~23) | 22 |
| m | Minute in hour | 30 |
| s | Second in minute | 55 |
| S | Millisecond | 234 |
| E | Day in week | Tuesday |
| D | Day in year | 360 |
| F | Day of week in month | 2 (second Wed. in July) |
| w | Week in year | 40 |
| W | Week in month | 1 |
| a | A.M/P.M marker | PM |
| k | Hour in day (1~24) | 24 |
| K | Hour in A.M/P.M (0~11) | 10 |
| z | Time zone | Eastern Standard Time |
| ' | Escape for text | Delimiter |
| " | Single quote | ' |
Source Code:
import java.util.*;
import java.text.*;
public class DateFormat {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}Result:
Watch the video:
Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

