Udemy logo

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.

Character Description Example
c Complete date and time Mon May 26 09:12:52 CDT 2014
F ISO 8601 date 2014-05-26
D  U.S. formatted date (month/day/year) 05/26/2014
T  24-hour time 18:05:19
r  12-hour time 06:05:19 pm
R 24-hour time, no seconds 18:05
Y Four-digit year (with leading zeroes) 2014
y Last two digits of the year (with leading zeroes) 14
C First two digits of the year (with leading zeroes) 20
B Full month name March
b Abbreviated month nam Mar
m Two-digit month (with leading zeroes) 09
d Two-digit day (with leading zeroes) 03
e Two-digit day (without leading zeroes 9
A Full weekday name Monday
a Abbreviated weekday name Mon
j  3 digit day of year (with leading zeroes) 069
H 2 digit hour (with leading zeroes), between 00 and 23 08
k 2 digit hour (without leading zeroes), between 0 and 23 8
I 2 digit hour (with leading zeroes), between 01 and 12 07
l 2 digit hour (without leading zeroes), between 1 and 12 7
M 2 digit minutes (with leading zeroes) 09
S 2 digit seconds (with leading zeroes) 33
L 3 digit milliseconds (with leading zeroes) 018
N 9 digit nanoseconds (with leading zeroes) 047000000
P Uppercase morning or afternoon marker AM/ PM
p Lowercase morning or afternoon marker am/ pm
z RFC 822 numeric offset from GMT -0800
Z Time zone PST

 

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.

Page Last Updated: May 2014

Top courses in Java

Java Interview Help
Bharath Thippireddy
4.6 (1,181)
Java Programming for Complete Beginners
in28Minutes Official
4.5 (38,838)
Oracle Java Certification - Pass the Associate 1Z0-808 Exam.
Tim Buchalka's Learn Programming Academy, Goran Lochert
4.5 (5,376)
Bestseller
Java for Absolute Beginners
Nick H
4.6 (7,445)
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.5 (3,636)
Bestseller
Learn Selenium with Java, Cucumber + Live Project
Pavan Kumar
4.6 (4,248)
Bestseller
Java SE 11 Developer 1Z0-819 OCP Course - Part 2
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.3 (993)
Core Java Made Easy (Covers the latest Java 17)
Bharath Thippireddy
4.5 (14,220)
Java Tutorial for Beginners
Navin Reddy
4.5 (525)

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo