Format time and date in JavaIt can be a chore to format time and date in Java. Sometimes you end up even trying to od it with a regular expression. This is a mistake, and will cause you a lot of headache. There is a much better way, using Java’s built in classes for Date and SimpleDateFormat. In this very short tutorial, I will show you how.

How to format time and date in Java

In Java, like in so many other programming languages, you often need to format time and date. This can be a hassle if you dont know the correct built-in classes for doing so. If you do, however, it becomes a breeze.

Start with a Date object

Date now = Calendar.getInstance().getTime();

Format with a SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

dateFormat.format(now);

And there you have it, your date will now be formatted as “2013-03-26 11:15:53”. Using the SimpleDateFormat patterns, you can format a date in almost any way you want. Easy peasy. Have a look at the table below for how it’s done.

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 199696
M Month in year Month JulyJul07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text TuesdayTue
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard TimePSTGMT-08:00
Z Time zone RFC 822 time zone -0800