How to convert a String to a Date

In this blog post, I will be demonstrating how you can convert a String to a Date object. Consider the following code snippet:

public class StringToDate {public static void main(String[] args) {System.out.println("Enter a date:");Scanner scanner = new Scanner(System.in);String dateStr = scanner.nextLine();System.out.println("Input date is "+dateStr);SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");try {Date date = simpleDateFormat.parse(dateStr);System.out.println("Date in date format is "+date);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}scanner.close();}}

The input Date in String format is read using the Scanner class. The code uses the SimpleDateFormat class. This is a class that provides date formatting functions. In the constructor, you need to specify the format in which the input date is specified as a String. So in this case, I have specified “dd-MM-yyyy” which means the date will be in this format. Then, the parse method is invoked. This method is defined in the DateFormat class which is a super-class of SimpleDateFormat . This returns a Date object corresponding to the input String.

 

So if you run this code with the input as “08-09-2018“, it will print the following output:

Enter a date:08-09-2018Input date is 08-09-2018Date in date format is Sat Sep 08 00:00:00 IST 2018

Note that the input date should match the format that is specified in the SimpleDateFormat constructor. Suppose we specify as input like this “08-Sep-18“, and if you run the code now, it will print the following:

Enter a date:08-Sep-18Input date is 08-Sep-18java.text.ParseException: Unparseable date: "08-Sep-18"at java.text.DateFormat.parse(Unknown Source)at learnjava.dates.StringToDate.main(StringToDate.java:17)

 

The API documentation for SimpleDateFormat  specifies the pattern Strings that you need to use for various date formats.

Comments

Popular posts from this blog

Java 8 DoubleFunction Example

How to convert a List to a Set

ArrayList Vs LinkedList