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


















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap