How do I convert String to Date object in Java?


The following code shows how we can convert a string representation of date into java.util.Date object.

To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.

And here is the result of our code:

The example starts by creating an instance of SimpleDateFormat with “dd/MM/yyyy” format which mean that the date string is formatted in day-month-year sequence.

Finally using the parse(String source) method we can get the Date instance. Because parse method can throw java.text.ParseException exception if the supplied date is not in a valid format; we need to catch it.

Here are the list of defined patterns that can be used to format the date taken from the Java class documentation.

LetterDate / Time ComponentExamples
GEra designatorAD
yYear1996; 96
MMonth in yearJuly; Jul; 07
wWeek in year27
WWeek in month2
DDay in year189
dDay in month10
FDay of week in month2
EDay in weekTuesday; Tue
aAm/pm markerPM
HHour in day (0-23)0
kHour in day (1-24)24
KHour in am/pm (0-11)0
hHour in am/pm (1-12)12
mMinute in hour30
sSecond in minute55
zTime zonePacific Standard Time; PST; GMT-08:00
ZTime zone-0800


Filed in: Java Text Package
© 8911 Java Examples - Built with love by Wayan Saryada.