
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
Add Minutes to Current Time Using Calendar.add() Method in Java
Java provides a built-in class called Calendar that allows developers to work with dates and times in their applications. The Calendar class provides various methods to manipulate dates and times, such as adding or subtracting days, months, years, hours, minutes, and seconds.
Problem Statement
Write a Java program to increment the current time by 10 minutes using the Calendar class.
OutputCurrent Date = Thu Nov 22 16:24:27 UTC 2018 Updated Date = Thu Nov 22 16:34:27 UTC 2018
Steps to add minutes to current time using Calendar.add() method
Below are the steps to add minutes to current time using Calendar.add() method
- Step 1: Import the Calendar class from the java.util package.
- Step 2: Create a Calendar object using the getInstance() method to get the current date and time.
- Step 3: Display the current date and time using the getTime() method.
- Step 4: Use the add() method with the Calendar.MINUTE constant to increment the current time by 10 minutes.
- Step 5: Display the updated date and time using the getTime() method.
Example
Given below is the Java program ?
import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.println("Current Date = " + calendar.getTime()); // Add 10 minutes to current date calendar.add(Calendar.MINUTE, 10); System.out.println("Updated Date = " + calendar.getTime()); } }
Output
Current Date = Thu Nov 22 16:24:27 UTC 2018 Updated Date = Thu Nov 22 16:34:27 UTC 2018
Code Explanation
Import the following package for Calendar class in Java.
import java.util.Calendar;
Firstly, create a Calendar object and display the current date and time.
Calendar calendar = Calendar.getInstance(); System.out.println("Current Date and Time = " + calendar.getTime());
Now, let us increment the minutes using the calendar.add() method and Calendar.HOUR_OF_DAY constant.
calendar.add(Calendar.MINUTE, 10);
Advertisements