Search code examples
javaparsingdate

Add a date to now by parsing the input


I'm trying to parse date in the future.

I'd like to add a parsed date to the current date (to have it in the future). The problem is that I can have many kind of date format, like:

  • dd
  • MM-dd
  • yyyy-MM-dd

So if the user set something like 5, the returned date will be (in our timelapse) 2011-11-05. If he set 02-14, it will be 2012-02-14.

But suppose we are the 4th of November, and the user set 11-03, it will be 2012-11-03 and not 2011-11-03 since it's past.

I tried to play with Calendar, Date, SimpleFormat, but I cannot make it work. My parsers (using SimpleDateFormat) are working though.

How can I achieve this?


Solution

  • I have had very good experience with jodatime - http://joda-time.sourceforge.net/. Checkout the Dateformatters in that.

    It has a very extensive API and lets you do things like add and subtract dates - taking into account timezones and daylight saving etc.