-1
String dt="2014-04-25";

I want to add n number of days in this date ... I have searched a lot but was not able to get any good working code....

I have tried SimpleDateFormat but it is not working so please help me with the code....

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Ayush Jain
  • 79
  • 3
  • 7
  • Post what you tried and explain what exactly was not working. – PM 77-1 Apr 07 '14 at 16:10
  • 1
    _in this date_ : dt is a String. Do you want a `Date` or a `String` ? – JGeo Apr 07 '14 at 16:11
  • `simpledateformat` is used to create different formats of dates, not to change time represented by it. Have you tried anything beside it? There are lot of suggestions of similar questions at the right side of this page, have you read them? – Pshemo Apr 07 '14 at 16:12
  • Sorry actually i have deleted that code :( :( that's why i have not posted that code – Ayush Jain Apr 07 '14 at 16:12
  • dt is the parameter i have passed from one page to java servlet in string form . – Ayush Jain Apr 07 '14 at 16:14

2 Answers2

0

You can do it using joda time library

import org.joda.time;

String dt="2014-04-25";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dateTime = formatter.parseDateTime(dt);

DateTime oneDayPlus = dateTime.plusDays(1);
String oneDayPlusString = oneDayPlus.toString(formatter);  // This is "2014-04-26"

oneDayPlus would give you the object you need.

Again, this needs you to use an extra jar file, so use it if you can introduce adding a new library.

Anoop
  • 5,540
  • 7
  • 35
  • 52
0

Remember String != Date they don't have anything in common (ok, exclude the fact that a string could represent a Date ok?)

If you want to add days to a String you could convert it to a Date and use normal APIs to add days to it.

And here we use SimpleDateFormat which is used to create from a patten string a date

String dt = "2014-04-25";
//           yyyy-MM-dd
//           year-month-day

DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

try
{
    Date date = format.parse(dt);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    calendar.add(Calendar.DAY_OF_MONTH, 5);

    System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e)
{
    System.out.println("Wrong date");
}

yyyy-MM-dd is our patten which corrisponds to our string.

format.parse(dt);

wil try to create a Date object from the string we passed, if it fails it throw an ParseException. (If you want to check if it works just try to pass an invalid string)

Then we create a new Calendar instance and set the date to the date we created (which corrisponds to the the date in our string) and add five days to our date.. and here we go. Now calendar will refer to the 30-04-2014.

You can replace the

calendar.add(Calendar.DAY_OF_MONTH, 5);

with

calendar.add(Calendar.DAY_OF_MONTH, n);

If you want and it will add n days.

Marco Acierno
  • 14,682
  • 8
  • 43
  • 53