Home Tutorial Java Core Java subtract days from date

 
 

Java subtract days from date
Posted on: October 12, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to subtract days from date.

Java subtract days from date

In this tutorial, you will learn how to subtract days from date.

Using the Calendar class, you can add and subtract date with the add() method. To subtract date, value should be passed with negative(-). This will reduce date from date. Here, we are going to subtract few days from current date and return the date of that day. For this, we have created a calendar instance and get a date to represent the current date. Then using the method add() of Calendar class, we have subtracted 4 days from the calendar and using the Date class, we have got the date of that day.

Example:

import java.util.*;

public class SubtractDaysFromDate{

  public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    Date today = calendar.getTime();
    System.out.println("Today's Date: " + today);
    calendar.add(Calendar.DAY_OF_YEAR, -4);
    Date datedays = calendar.getTime();
    System.out.println("Date before 4 days: " + datedays);
  }
}

Output:

Today's Date: Fri Oct 12 12:39:55 IST 2012
Date before 4 days: Mon Oct 08 12:39:55 IST 2012
Advertisement

Related Tags for Java subtract days from date:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 12, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com