by Sai gowtham

How to convert String to Date in Java

To convert a string to date we can use the SimpleDateFormat class in Java.

Here is an example, which converts the string to date of a format yyyy-mm-dd.

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class Main
{
   public static void main(String[] args) {

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");            String dateInString = "2020-01-12";
        try {

            Date date = formatter.parse(dateInString);            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }
   }
}

Output:

Sun Jan 12 00:01:00 UTC 2020

2020-01-12
  1. Date and Time Patterns

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course