×

How to Convert String to Date in Java

How to Convert String to Date in java

You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes. Both classes belong to java.text package. The SimpleDateFormat class is used to both parse and format dates according to the formatting pattern specified by you.

You can create a SimpleDateFormat instance like this:

String pattern = "yyyy-MM-dd";

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

The pattern parameter passed to the constructor of the SimpleDateFormat class. The pattern is used for formatting and parsing of dates.

Remember

There is a little bit confusion between “m” and “M”, “m” represents a minutes while “M” represents the Month. Similarly “d” represents a date in the month while “D” represents Day of the week. This is the most common cause of error while converting String to Date.  In short, ddMMyy is not equal to DDmmyy.

Example

In this example, Datestr is a variable of String type contains a string “23/05/2019”. The date is a variable of type Date stores the converted value of Datestr. A new is a keyword that creates the constructor of the SimpleDateFormat class and parses the date format as an argument. parse() is a method of SimpleDateFormat class and parses Datestr as an argument which is to be converted into Date. The println statement prints the converted value of Datestr.

The parse() method throws an exception java.text.ParseException, to remove this exception you should use either try catch block or simply write throws Exception after the main method.

import java.text.SimpleDateFormat; 
import java.util.Date; 
public class StringtoDateExample
{ 
public static void main(String[] args)throws Exception
{ 
String Datestr="23/05/2019"; 
Date date=new SimpleDateFormat("dd/MM/yyyy").parse(Datestr); 
System.out.println(date); 
} 
}

Output

Thu May 23 00:00:00 IST 2019

Let’s see another example in which different date format is used.

Example

import java.text.SimpleDateFormat;  
import java.util.Date;  
public class StringToDateExample2 
{  
public static void main(String[] args)throws Exception 
{  
String Datefrmt1="31/12/1998";  
String Datefrmt2= "23-May-2019";  
String Datefrmt3= "05 23, 2019";  
String Datefrmt4= "Thu, May 23 2019";  
String Datefrmt5 = "Thu, May 23 2019 21:31:20";  
String Datefrmt6 = "23-May-2019 21:31:20";  
SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");  
SimpleDateFormat formatter2=new SimpleDateFormat("dd-MMM-yyyy");  
SimpleDateFormat formatter3=new SimpleDateFormat("MM dd, yyyy");  
SimpleDateFormat formatter4=new SimpleDateFormat("E, MMM dd yyyy");  
SimpleDateFormat formatter5=new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss");  
SimpleDateFormat formatter6=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");  
Date date1=formatter1.parse(Datefrmt1);  
Date date2=formatter2.parse(Datefrmt2);  
Date date3=formatter3.parse(Datefrmt3);  
Date date4=formatter4.parse(Datefrmt4);  
Date date5=formatter5.parse(Datefrmt5);  
Date date6=formatter6.parse(Datefrmt6);  
System.out.println(Datefrmt1+"\t"+date1);  
System.out.println(Datefrmt2+"\t"+date2);  
System.out.println(Datefrmt3+"\t"+date3);  
System.out.println(Datefrmt4+"\t"+date4);  
System.out.println(Datefrmt5+"\t"+date5);  
System.out.println(Datefrmt6+"\t"+date6);  
}  
}

Output

23/05/2019 Thu May 23 00:00:00 IST 2019
23-May-2019 Thu May 23 00:00:00 IST 2019
05 23, 2019 Thu May 23 00:00:00 IST 2019
Thu, May 23 2019 Thu May 23 00:00:00 IST 2019
Thu, May 23 2019 21:31:20 Thu May 23 21:31:20 IST 2019
23-May-2019 21:31:20 Thu May 23 21:31:20 IST 2019

Related Topics

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.