Increment Date String by 1 Day
I have a date String newDate = "31.05.2001"
which I have to increment by 1 开发者_StackOverflow社区day.
I tried the following code:
String dateToIncr = "31.12.2001";
String dt="";
SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dateToIncr));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 1); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("final date now : " + dt);
But with this code, it is only managing to add the DAY i.e output of 31.05.2001 will be 1.05.2001 keeping the month and the year unchanged! Please help me with this.
I've also tried
c.roll(Calendar.DATE, 1); // number of days to add
You should use new SimpleDateFormat("dd.MM.yyyy");
'mm' means minutes, 'MM' is months.
It would be simpler for you to make it into a java Date
object and use DateUtils
from Apache on it for various operations. Check this http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write ridiculous number of lines for this every time.
The API says:
addDays(Date date, int amount) : Adds a number of days to a date returning a new object.
Note that it returns a new Date
object and does not make changes to the previous one itself.
Your mistake is in date format. You should use MM (month) instead of mm (minutes).
Change SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
to SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
and enjoy.
try this out!!!!
String DATE_FORMAT = "dd-MM-yyyy";
String date_string = "20-12-2001";
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat(DATE_FORMAT);
Date date = (Date)sdf.parse(date_string);
Calendar c1 = Calendar.getInstance();
c1.setTime(date);
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH,1);
System.out.println("Date + 1 month is : " + sdf.format(c1.getTime()));
精彩评论