java

How to Convert a String to a Date in Java

In this tutorial, we are going to see how to convert a String to a date in Java. We can convert String to Date in java using the parse() method of DateFormat and SimpleDateFormat classes.
 

Method 1: How to Convert a String to a Date in Java
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
	public static void main(String[] args)throws Exception {
		String str = "29/11/2020";
		Date date = new SimpleDateFormat("dd/MM/yyyy").parse(str);
		System.out.println(str+" "+date);
	}
}

Output:

29/11/2020 Sun Nov 29 00:00:00 UTC 2020

 
[st_adsense]  

Method 2: How to Convert a String to a Date in Java
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;

public class Main {

    public static void main(String[] args) {
        String str = "2020-11-29";
        LocalDate date = LocalDate.parse(str, DateTimeFormatter.ISO_DATE);
        System.out.println(date);
    }
}

Output:

2020-11-29

In the above code, we have used the predefined ISO_DATE formatter which takes the date string in the format 2020-11-29.
 
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *