Caution: SimpleDateFormat

Every day at work teaches you something or the other. Today I learned something patterns, in general. A pattern used in a certain API doesn’t always consort with common sense. You actually should read the API first before using it in your application.
In case you are into java, then you must have heard or even used a SimpleDateFormat. A SimpleDateFormat is widely used to convert a String into a Date(java.util.Date) according to a pattern.


String dateAsString = “2012-01-06 12:23:34”;
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
Date newDate = sdf.parse(dateAsString);

NOTE: the parse function may throw a ParseException in case the String provided to it as an argument is not in the given format.

Simple, isn’t it. But one thing most people miss out on is the pattern. SimpleDateFormat takes hh as hours in the 0 to 12 format and not in the 0-24 hrs format. So, the date “2012-01-06 12:23:34” will be simply converted to “2012-01-06 00:23:34”. However, if you input anything other than 12 in hours, it would act normal. So just think, you’ll never know what hit you, unless you use, “HH” instead of “hh”.

For more on this, read the documentation..


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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: