Convert String Date to Date Object in Java


In order to convert a String to Java Date Object, we can make use of the SimpleDateFormat, let us see some examples,

Example 1: Convert 2022-08-26 to Java Date

public static void main(String[] args) throws ParseException {
    String dateStr = "2022-08-26";
   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = simpleDateFormat.parse(dateStr);
    System.out.println(date);
}
Output:
Fri Aug 26 00:00:00 CST 2022

Note if you do not provide the correct format, you will get an ParseException. Make sure you know what is the date and month fields, if you have a date like 2022-01-02 its hard to say which is month and which is a year unless you have complete information!

Example:
Exception in thread "main" java.text.ParseException: Unparseable date: "202208-26"
 at java.text.DateFormat.parse(DateFormat.java:366)
 at com.example.demo.JavaStreamFiltersExamples.main(JavaStreamFiltersExamples.java:18)

✏️ You can follow this page to see a comprehensive list of all Date formats: List of Simple Date Formats

Cheatsheet Java Simple Date Format List
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.