Slide 1
Slide 2
Slide 3

Date Formatting Using printf in java programming (V29)

No Comments

Date Formatting Using printf

Date and time formatting can be displayed easily by using the printf method. You use a two-letter format that begins with t and ends with one of the characters from the table as shown in the code below:

Date and Time Conversion Characters

Character Description Example
cComplete date and timeMon May 04 09:51:52 ICT 2009
FISO 8601 date2004-02-09
DU.S. formatted date (month/day/year)02/09/2004
T24-hour time18:05:19
r12-hour time06:05:19 pm
R24-hour time, no seconds18:05
YFour-digit year (with leading zeroes)2004
yLast two digits of the year (with leading zeroes)04
CFirst two digits of the year (with leading zeroes)20
BFull month nameFebruary
bAbbreviated month nameFeb
mTwo-digit month (with leading zeroes)02
dTwo-digit day (with leading zeroes)03
eTwo-digit day (without leading zeroes)9
AFull weekday nameMonday
aAbbreviated weekday nameMon
jThree-digit day of year (with leading zeroes)069
HTwo-digit hour (with leading zeroes), between 00 and 2318
kTwo-digit hour (without leading zeroes), between 0 and 2318
ITwo-digit hour (with leading zeroes), between 01 and 1206
lTwo-digit hour (without leading zeroes), between 1 and 126
MTwo-digit minutes (with leading zeroes)05
STwo-digit seconds (with leading zeroes)19
LThree-digit milliseconds (with leading zeroes)047
NNine-digit nanoseconds (with leading zeroes)047000000
PUppercase morning or afternoon markerPM
pLowercase morning or afternoon markerpm
zRFC 822 numeric offset from GMT-0800
ZTime zoneICT
sSeconds since 1970-01-01 00:00:00 GMT1078884319
QMilliseconds since 1970-01-01 00:00:00 GMT1078884319047

Source Code:

Copied!
import java.util.Date;
public class CurrentDate {

   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();

      // display time and date
      String str = String.format("Current Date/Time : %tc", date );

      System.out.printf(str);
   }
}

Result:


        It becomes slightly complex if you need to supply the same date multiple times to format each part separately. For this reason, the format string can display the index of the argument that should be formatted.
        The index must use the % symbol and must be followed by a $ symbol.

Source Code:

Copied!
import java.util.Date;
public class DueDate {

   public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();
  
      // display time and date
      System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);
   }
}

Result:

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top