How to convert a String to a Date in Java

Java uses the SimpleDateFormat to parse dates from a String to a Date object.

Syntax:

Date date = null;

try {
  date = new SimpleDateFormat("yyyy-MM-dd").parse( "2017-05-09" );
} catch (ParseException e1) {
  e1.printStackTrace();
}

Example:

This example first creates the String to parse "2017-05-09", then the formatter Object of type SimpleDateFormat is created to parse the date. The method parse is called with the String as a parameter. The output value is stored in the date variable. That variable is then written in the output. If the String passed in not in the format defined by the pattern of the formatter, an exception is thrown.

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

public class DateStringFormatting {

	public static void main(String[] argv){
		String dateString = "2017-05-09";

		String pattern = "yyyy-MM-dd";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		
		Date date = null;
		
		try {
			date = simpleDateFormat.parse( dateString );
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		System.out.println( "Formatted date: " + date ); 
	}
	
}

The output will be:

	
Formatted date: Tue May 09 00:00:00 PDT 2017
	

References:

SimpleDateFormat

Download:

Download

Share this article:

Recent Comments