Home > Java > javaTutorial > body text

How to Subtract Days from a Date Using Java\'s Calendar Class?

Mary-Kate Olsen
Release: 2024-11-22 08:52:09
Original
569 people have browsed it

How to Subtract Days from a Date Using Java's Calendar Class?

Java Calendar: Subtracting Days from a Date

Subtracting a specified number of days from a date can be accomplished with Java's Calendar class. While there's no dedicated function for this purpose, the add() method offers a flexible solution.

Solution:

To subtract "X" days from a date, utilize the following approach:

Calendar calendar = Calendar.getInstance(); // Default to current date and time
calendar.add(Calendar.DAY_OF_MONTH, -X); // Subtract "X" days
Copy after login

This operation modifies the calendar object directly, adjusting its date field by subtracting the specified number of days. The result is a date that is "X" days earlier than the original.

The above is the detailed content of How to Subtract Days from a Date Using Java\'s Calendar Class?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template