Incremental date string for 1 day

I have a date String newDate = "31.05.2001"

which I should increase by 1 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 the help of this code, just to add a DAY, ie the output of 05/31/2001 will be 05/05/2001, keeping the month and year unchanged! Please help me with this.

I also tried

 c.roll(Calendar.DATE, 1); // number of days to add 
+6
source share
4 answers

You should use new SimpleDateFormat("dd.MM.yyyy");

'mm' means minutes, 'MM' means months.

+12
source

It will be easier for you to do this in a java Date object and use DateUtils from Apache for it for various operations. Check out http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/time/DateUtils.html . This is especially convenient when you need to use it in several places in your project and not want to write a ridiculous number of lines for this every time.

API says:

addDays (Date, int count): adds a few days to the date returning a new object.

Note that it returns a new Date object and does not make changes to the previous one.

+3
source

Your error is in date format. You should use MM (month) instead of mm (minutes).

Change SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy"); on SimpleDateFormat sdf = new SimpleDateFormat ("dd.MM.yyyy");

and enjoy.

+2
source

try it!!!!

 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())); 
+2
source

Source: https://habr.com/ru/post/892649/


All Articles