How to convert String to Date in Java

Many time developers face problem while woking with string and date especially while converting date from string and vice versa. In this article, you will learn how to convert string to date in Java.

Before we understand how to convert string to Date in Java, let us  first discuss various date formats most commonly used and their representational format.

Representational Format Date
dd-MMM-yyyy 07-Nov-1990
dd/MM/yyyy 07/11/1990
MMM dd, yyyy Nov 07, 1990
E, MMM dd yyyy Fri, Nov 07 1990
EEEE, MM dd, yyyy HH:mm:ss a Friday, Jun 07, 1990 10:10:10 AM

Program to Convert String to Date

In the below code, I'll convert various given string to corresponding date object using parse() method of SimpleDateFormat class.  

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

public class DateExample {

	public static void main(String[] args) {
		
		//dd-MMM-yyyy
		String stringDate1 = "7-Jun-2013";
		String format1 = "dd-MMM-yyyy";
		convertStringToDate(stringDate1, format1);
		
		//dd/MM/yyyy
		String stringDate2 = "07/11/2013";
		String format2 = "dd/MM/yyyy";
		convertStringToDate(stringDate2, format2);
		
		
	}
	public static void convertStringToDate(String stringDate, String format){
		
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		try {

			Date date = formatter.parse(stringDate);         //Line 1
			System.out.println(date);
			System.out.println(formatter.format(date));
                        System.out.println("------------------------");
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

Output

Fri Jun 07 00:00:00 IST 2013
07-Jun-2013
------------------------
Thu Nov 07 00:00:00 IST 2013
07/11/2013
------------------------

In the above code snippet, we first created SimpleDateFormat object using the format of date represented by string. Now the SimpleDateFormat object is used to parse the given string to date object as shown in line 1.

Similarly now try to convert various strings (refer above table to create string representing date format) and try to convert it to date object using above code snippet. In the above article, you learned how to convert string to date in Java using parse() method of SimpleDateFormat class.

Article tagged as
Author
Author: Amit Gupta
Published On: 27/11/2015
Last revised On: 28/11/2015
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media