How to subtract X days from a date using Java calendar?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In Java, working with dates and calendars is a common task, especially when you need to manipulate dates by adding or subtracting days. The Java Calendar class, part of the java.util package, provides a powerful API for date-time operations. This article delves into the details of subtracting a specified number of days from a given date using the Calendar class.
Using Java Calendar to Subtract Days
The Calendar class in Java is both flexible and robust for handling date manipulations. Here's a step-by-step guide on how to subtract days from a given date.
Step-by-Step Process
- Instantiate a Calendar Object:
- First, create an instance of
Calendarby getting a calendar instance:
- Set a Specific Date (Optional):
- If you want to work with a specific date rather than the current date, set the desired date using
Calendar.set():
- Subtract Days:
- Use the
add()method to subtract days. Theadd()method accepts the calendar field and the amount to add (or subtract if negative):
- In this example, 5 days are subtracted from the date.
- Retrieve the Updated Date:
- Obtain the date after subtraction using the
getTime()method, which returns aDateobject:
Example Program
Here's a complete example demonstrating how this is accomplished:
Technical Explanation
- The
Calendarclass provides various constants likeCalendar.DAY_OF_MONTHwhich acts as keys when modifying specific time fields. - The
add()method is flexible, allowing you to adjust any field of the calendar (e.g., year, month, day, etc.) incrementally. - Instead of subtracting days manually, leveraging the
add()method handles day overflow, dealing efficiently with end-of-month transitions and leap years.
Advantages
- Ease of Use: The
Calendarclass abstracts complex date manipulations, making operations straightforward. - Time Zone Handling: It considers the default time zone or a specified one, ensuring consistent date calculations.
- Automatic Field Update: When adding or subtracting, related fields such as the year or day are automatically adjusted, preventing errors like "February 30th."
Limitation
- Legacy API:
Calendaris part of Java's older date-time classes. Since Java 8, thejava.timepackage offers more modern approaches, althoughCalendarremains in use for legacy systems.
Comparison with Java 8 Date-Time API
Java 8 introduced a new date-time API with the java.time package, which offers an even more intuitive method of handling date operations. Below is a comparison of subtracting days using both Calendar and the newer java.time.LocalDate:
| Feature | Calendar | java.time.LocalDate |
| Syntax and Usability | More verbose and outdated | Modern and concise |
| Date Subtraction Example | calendar.add(Calendar.DAY_OF_MONTH, -days); | localDate.minusDays(days); |
| Time Zone Awareness | Yes | Yes (with ZonedDateTime) |
| Leap Year Handling | Automatic | Automatic |
| Concurrent Access | Mutable and not thread-safe | Immutable and thread-safe |
By using java.time.LocalDate, the code for subtracting days becomes:
Conclusion
Subtraction of days from a date using the Java Calendar class involves setting up a calendar instance, subtracting the desired number of days, and retrieving the result. While Calendar remains useful, especially for backward compatibility, modern applications can benefit from the cleaner syntax and improved functionalities of the Java 8 java.time package. The choice depends on your project's requirements and compatibility needs.
Related reading
- How to supply value to an annotation from a Constant java
- How to synchronize a static variable among threads running different instances of a class in Java?
- How to tell a Mockito mock object to return something different the next time it is called?
- How to tell Jackson to ignore a field during serialization if its value is null?
- How to test a component / bean in Spring Boot
- How to test Classes with ConfigurationProperties and Autowired
- How to test code dependent on environment variables using JUnit?
- How to test main class of Spring-boot application

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.