Wednesday 18 May 2016

Adding days to a date in Java


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * To add days in date
 * @author rajesh.kumar
 */
public class AddingDaysInDate {


      public static void main(String[] args) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Calendar calendar = Calendar.getInstance();

            // Set current date in calendar instance.
            calendar.setTime(new Date());

            int days = 10;
            // Adding 10 days
            calendar.add(Calendar.DATE, days);
           
            String output = sdf.format(calendar.getTime());
            System.out.println("Date after "+days+ " : "+output);
           
           
            days = -10;
            // Adding 10 days
            calendar.add(Calendar.DATE, days);
           
            output = sdf.format(calendar.getTime());
            System.out.println("Date "+ Math.abs(days) + " before : "+output);

      }
}

Output:
      Date after 10 : 28/05/2016
      Date 10 before : 18/05/2016

           

void java.util.Calendar.add(int field, int amount)
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar.

add(Calendar.DAY_OF_MONTH, -5).

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...