java date minus 1 day

www.l‮ttua‬uri.com
java date minus 1 day

In Java, you can use the java.util.Calendar class to subtract a specified number of days from a java.util.Date object.

Here is an example of how to subtract one day from a Date object using the Calendar class in Java:

import java.util.Calendar;
import java.util.Date;

public class Main {
  public static void main(String[] args) {
    // Create a Calendar instance
    Calendar cal = Calendar.getInstance();

    // Set the Calendar to the current date and time
    cal.setTime(new Date());

    // Subtract one day from the Calendar
    cal.add(Calendar.DATE, -1);

    // Get the modified date from the Calendar
    Date date = cal.getTime();

    // Print the modified date
    System.out.println("Date minus one day: " + date);  // Output: current date minus one day
  }
}

In this example, we create a Calendar instance and set it to the current date and time using the setTime method. We then use the add method to subtract one day from the Calendar, and use the getTime method to get the modified date as a Date object.

You can use the add method to add or subtract any unit of time, such as days, months, or years, by specifying the appropriate field constant. For example, you can use the Calendar.MONTH constant to add or subtract months, or the Calendar.YEAR constant to add or subtract years.

Created Time:2017-11-03 00:14:53  Author:lautturi