How to Convert String to Date in Java

Facebooktwitterredditpinterestlinkedinmailby feather

How to Convert String to Date in java

You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes. Both classes belong to java.text package. The SimpleDateFormat class is used to both parse and format dates according to the formatting pattern specified by you.

You can create a SimpleDateFormat instance like this:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

The pattern parameter passed to the constructor of the SimpleDateFormat class. The pattern is used for formatting and parsing of dates.

Remember

There is a little bit confusion between “m” and “M”, “m” represents a minutes while “M” represents the Month. Similarly “d” represents a date in the month while “D” represents Day of the week. This is the most common cause of error while converting String to Date.  In short, ddMMyy is not equal to DDmmyy.

Example

In this example, Datestr is a variable of String type contains a string “23/05/2019”. The date is a variable of type Date stores the converted value of Datestr. A new is a keyword that creates the constructor of the SimpleDateFormat class and parses the date format as an argument. parse() is a method of SimpleDateFormat class and parses Datestr as an argument which is to be converted into Date. The println statement prints the converted value of Datestr.

The parse() method throws an exception java.text.ParseException, to remove this exception you should use either try catch block or simply write throws Exception after the main method.

Output

Let’s see another example in which different date format is used.

Example

Output

Facebooktwitterredditpinterestlinkedinmailby feather