TechTip: Use of setLenient method on SimpleDateFormat

Some times, when you are parsing a date string against a pattern(such as MM/dd/yyyy) using java.text.SimpleDateFormat, strange things might happen(for unknown developers) if your date string is a dynamic content entered by user in some input field on the user interface and if it is not entered in the specified format.

The parse method, in the SimpleDateFormat parses the date string, which is in incorrect format and returns you date object, instead of throwing a java.text.ParseException. However, the date returned is not what is expected by you.

The below code-snippet shows you this behaviour.

package com.starwood.system.util;

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

public class DateSample {

	public static void main(String args[]){
		SimpleDateFormat sdf = new SimpleDateFormat () ;
		sdf.applyPattern("MM/dd/yyyy") ;
		try {
			Date d = sdf.parse("2011/02/06") ;
			System.out.println(d) ;
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

}

Output: Thu Jul 02 00:00:00 MST 173

See the output, that is a date back in the year 173.

To avoid this problem, call the setLenient (false) on SimpleDateFormat instance. That will make the parse method to throw ParseException when the given input string is not in the specified format.

Here is the modified code-snippet.

package com.starwood.system.util;

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

public class DateSample {

	public static void main(String args[]){
		SimpleDateFormat sdf = new SimpleDateFormat () ;
		sdf.applyPattern("MM/dd/yyyy") ;
		sdf.setLenient(false) ;
		try {
			Date d = sdf.parse("2011/02/06") ;
			System.out.println(d) ;
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

}

Output:
java.text.ParseException: Unparseable date: "2011/02/06"
	at java.text.DateFormat.parse(Unknown Source)
	at com.starwood.system.util.DateSample.main(DateSample.java:14)
Bookmark and Share

3 Responses to TechTip: Use of setLenient method on SimpleDateFormat

  1. Yosep says:

    Thanks for this share!

  2. Amar Panigrahy says:

    Thanks for the explanation.

  3. Rakesh says:

    Thanks for the explanation.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>