Java Date Format – Using Format Codes to Get the Date You Want

java string to byte arrayJava is a platform-independent and object oriented programming language.  This language was initially developed by Sun Microsystems. Since its release in 1995, Java has undergone several revisions.  It is easy to learn and is presently one of the world’s most popular programming languages.  Java programs are compiled into platform-independent byte code. This code is interpreted by JVM(Java Virtual Machine) of the platform its run on. The language is robust and incorporates the state-of-the-art security features.  It is used to develop web applications as well as standalone applications.  Java programs have automatic memory management.

In this beginner’s level tutorial, we take you through how to format a Date object in the Java programming language. We assume that you are familiar with the basics of programming. If you’re new to Java programming, take this beginners course to get started.

Date Class in Java

The Date class in Java is contained in the java.util package. The current date and time are encapsulated in Date class. This class has two constructors. The first constructor assigns the object the system date and time. The syntax is as follows

Date()

The second constructor accepts as a parameter the number of milliseconds that have elapsed since the date January 1, 1970. The syntax for this constructor is as follows:

Date(long millisec)

How to Format Dates in Java

In Java, the SimpleDateFormat is usually used to format a date. This class is subclass of DateFormat. Its format method converts a date to a string. On the other hand, its parse method converts a string to a date.

Example 1: Program to Get the Current Date and Time

import java.util.Date;
public class Example{
public static void main(String args[]) {
Date date1 = new Date();
System.out.println(date1.toString());
}
}

The import statement imports the classes from the date package. Once done, you can use the library’s classes in your program.  The name of the class used in this program is user defined and named Example. The keyword public is the access specifier that indicates everybody or any external class can instantiate this class. The keyword static is used to indicate there is only one instance of this class. In this program, we create a date object. The date object contains the current date and time. The toString() converts the date object into a string. This is printed on the screen. You can learn how to write your own Java programs with this course.

Example 2: Program to Format Date using SimpleDateFormat

SimpleDateFormat is a class responsible to format and parse dates. Let’s take a look at the program below to understand this better:

import java.util.*;
import java.text.*;
public class Example2 {
public static void main(String args[]) {
Date date1 = new Date( );
SimpleDateFormat x =  new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Today's Date: " + x.format(date1));
}
}

The output of the above program is Mon 2014.05.26 at 13:36:21 PM PDT . The line with SimpleDateFormat specifies how we want the date to be shown. The ‘E’, ‘yyyy.MM.dd’ are the codes indicating the specific format we want. Check out the table below to see the different format codes available.

Simple DateFormat format codes

This is the list of most commonly used format codes with dates in Java. You can use these format codes in your Java programs to convert the date to the desired  format.

Character                 Description                                           Example

G                               Era designator                                                   AD

y                               Year in four digits                                              2014

M                               Month in year                                                   May or 05

D                                Day in month                                                     26

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                                                       Monday

D                              Day in year                                                         360

F                             Day of week in month                                         2 (second Wed. in July)

w                           Week in year                                                          47

W                           Week in month                                                     3

a                            A.M./P.M. marker                                                PM

k                           Hour in day (1~24)                                               21

K                           Hour in A.M./P.M. (0~11)                                  10

z                            Time zone                                      Eastern Standard Time

‘                            Escape for text                                                        Delimiter

”                             Single quote                                                          `

If you’d like to understand more about the date format in Java, we suggest that you take this course on basics of Java Programming.

Example 3 : To Format and Print a Date using the printf Function

import java.util.Date;
public class Example3 {
public static void main(String args[]) {
Date date1 = new Date();
String new_str = String.format("Current Date/Time : %tc", date1 );
System.out.printf(new_str);
}
}

The string.format() function converts date1 from date format to string format. Then the printf() function prints the string passed to it as parameter to the output screen. The output of the above program is

Current Date/Time : Mon May  26 13:49:15 MST 2014

Advanced Date and Time Conversion Code

Like we mentioned earlier, Java is a pretty flexible language and gives you many ways to customize what you want. The list we gave above is of the most commonly used date-time format codes, but does not provide a complete range of possible formats for dates. Yes, there are more. Check out the table below for the more advanced date formatting codes.

CharacterDescriptionExample
cComplete date and timeMon May 26 09:12:52 CDT 2014
FISO 8601 date2014-05-26
D U.S. formatted date (month/day/year)05/26/2014
T 24-hour time18:05:19
r 12-hour time06:05:19 pm
R24-hour time, no seconds18:05
YFour-digit year (with leading zeroes)2014
yLast two digits of the year (with leading zeroes)14
CFirst two digits of the year (with leading zeroes)20
BFull month nameMarch
bAbbreviated month namMar
mTwo-digit month (with leading zeroes)09
dTwo-digit day (with leading zeroes)03
eTwo-digit day (without leading zeroes9
AFull weekday nameMonday
aAbbreviated weekday nameMon
j 3 digit day of year (with leading zeroes)069
H2 digit hour (with leading zeroes), between 00 and 2308
k2 digit hour (without leading zeroes), between 0 and 238
I2 digit hour (with leading zeroes), between 01 and 1207
l2 digit hour (without leading zeroes), between 1 and 127
M2 digit minutes (with leading zeroes)09
S2 digit seconds (with leading zeroes)33
L3 digit milliseconds (with leading zeroes)018
N9 digit nanoseconds (with leading zeroes)047000000
PUppercase morning or afternoon markerAM/ PM
pLowercase morning or afternoon markeram/ pm
zRFC 822 numeric offset from GMT-0800
ZTime zonePST

 

Example 4: Program to Get the Complete Date and Time

import java.util.*;
import java.text.*;
public class Example4 {
   public static void main(String args[]) {
      Date date1 = new Date( );
      SimpleDateFormat x =  new SimpleDateFormat ("c");
      System.out.println("Current Date: " + x.format(date1));
   }
}

The output of this program will be Mon May 26 21:24:34 CDT 2014. That is, it will display the current date and time, along with time zone.

We’ve tried to give you a comprehensive view of how to format date in Java. Do try out these programs on your own to get a feel of it. Once you’re ready to move on to the next level, you can take this advanced course on Java.