Slide 1
Slide 2
Slide 3

Date Time Format in java programming (V28)

No Comments

 Date and Time

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:

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:

Copied!
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
GEra designatorAD
yYear in four digits2001
MMonth in yearJuly or 07
dDay in month10
hHour in A.M/P.M (1~12)12
HHour in day (0~23)22
mMinute in hour30
sSecond in minute55
SMillisecond234
EDay in weekTuesday
DDay in year360
FDay of week in month2 (second Wed. in July)
wWeek in year40
WWeek in month1
aA.M/P.M markerPM
kHour in day (1~24)24
KHour in A.M/P.M (0~11)10
zTime zoneEastern Standard Time
'Escape for textDelimiter
"Single quote'

Source Code:

Copied!
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

back to top