Joda vs SimpleDateFormat

Java developers who are used to Joda date time library has surprises while switching to the date library provided by Java. Here are few things to be aware while using SimpleDateFormat.

SimpleDateFormat is not as strict as a Joda date formatter. While parsing a string as a date given a date pattern Joda expects the date to be valid (E.g: 31-Feb-2017 is an invalid date), but by default, SimpleDateFormat can parse invalid dates defaulting to some values. However, the parsing can be made strict by using setLinient() method. When this flag is set to false, the parsing becomes strict thereby return null dates when parsing invalid dates.


Even when the setLinient is set to false, the parser will parse irrelevant characters after the length of the required date format.


Please refer to the below example.

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class SimpleDateFormatTest {

	public static void main(String[] args) {

		/*Linient Parsing*/
		final SimpleDateFormat formatterLinient = new SimpleDateFormat("M/d/yyyy", new Locale("en"));
		final ParsePosition posLinient = new ParsePosition(0);
		Date dateLinient = formatterLinient.parse("02/31/2016", posLinient);
		System.out.println(dateLinient); /* OUTPUT: Wed Mar 02 05:30:00 IST 2016 */

		/*Strict Parsing*/
		final SimpleDateFormat formatter = new SimpleDateFormat("M/d/yyyy", new Locale("en"));
		final ParsePosition pos = new ParsePosition(0);
		Date date = formatter.parse("31/02/2016", pos); //Passing an Invalid Date
		System.out.println(date); /*OUTPUT: null */

		/*Ignoring characters after the required format*/
		final SimpleDateFormat formatterJunkchars = new SimpleDateFormat("M/d/yyyy", new Locale("en"));
		final ParsePosition posJunkchars = new ParsePosition(0);
		Date dateposJunkchars = formatter.parse("02/03/2016JunkChars", posJunkchars);
		System.out.println(dateposJunkchars);/* OUTPUT: Wed Feb 03 05:30:00 IST 2016*/



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s