
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to subtract 1 year from the calendar
In this article, we will subtract one year from the calendar in Java. We will be using Calender class from the java.util package. The program captures the current date, subtracts one year from it, and then displays the updated date.
Problem Statement
Write a Java program to subtract one year from the calendar. Below is a demonstration of the same ?
Input
Current Date = Fri Nov 23 06:39:40 UTC 2018
Output
Updated Date = Thu Nov 23 06:39:40 UTC 2017
Steps to subtract 1 year from the calendar
Following are the steps to subtract 1 year from the calendar ?
- First, we will import the Calendar class from java.util package.
- Create a Calendar object by initializing the Calendar.getInstance() to get the current date and time.
- Display the current date by using calendar.getTime() to print the current date.
- Subtract 1 year, to do so we will use the calendar.add() method to decrease the year by 1.
- Display the updated date by printing the updated date with the calendar.getTime().
Java program to subtract 1 year from the calendar
The following is a Java program to subtract 1 year from the calendar ?
import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.println("Current Date = " + calendar.getTime()); // Subtract 1 year from the Calendar calendar.add(Calendar.YEAR, -1); System.out.println("Updated Date = " + calendar.getTime()); } }
Output
Current Date = Fri Nov 23 06:39:40 UTC 2018 Updated Date = Thu Nov 23 06:39:40 UTC 2017
Code Explanation
This program starts by importing the Calendar class from the java.util package, which provides various methods for handling date and time. We create a Calendar object using Calendar.getInstance(), which initializes the object with the current date and time. The current date is then retrieved and printed using the calendar.getTime() method.
To subtract one year from the current date, we use the calendar.add() method, where Calendar.YEAR specifies the field to be modified, and -1 indicates that we want to subtract one year. Finally, the updated date is printed using calendar.getTime(), showing the date one year earlier.