Java program to add,sub dates and display time in hours,mins,sec

Answers (1)

Here is a code to add/sub years, months, days hours, minutes, or seconds to a Date and time: 

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CalendarAddSubtractExample 
    public static void main(String[] args) 
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        System.out.println("Current Date " + dateFormat.format(date));

        // Convert Date to Calendar
        Calendar c = Calendar.getInstance();
        c.setTime(date);

        // Perform addition/subtraction
        c.add(Calendar.YEAR, 2);
        c.add(Calendar.MONTH, 1);
        c.add(Calendar.DATE, -10);
        c.add(Calendar.HOUR, -4);
        c.add(Calendar.MINUTE, 30);
        c.add(Calendar.SECOND, 50);

        // Convert calendar back to Date
        Date currentDatePlusOne = c.getTime();

        System.out.println("Updated Date " + dateFormat.format(currentDatePlusOne));
    

 

Preparation Products

Knockout NEET May 2023 (Easy Installments)

Personalized AI Tutor and Adaptive Time Table, Self Study Material, Weekend Live Classes, Mentorship from our Experts, Unlimited Mock Tests and Personalized Analysis Reports, 24x7 Doubt Chat Support,.

₹ 5499/-
Buy Now
Knockout JEE Main April 2021 (One Month)

Personalized AI Tutor and Adaptive Time Table, Self Study Material, Weekend Live Classes, Mentorship from our Experts, Unlimited Mock Tests and Personalized Analysis Reports, 24x7 Doubt Chat Support,.

₹ 14000/- ₹ 4999/-
Buy Now
Knockout NEET Aug 2021 (One Month)

Personalized AI Tutor and Adaptive Time Table, Self Study Material, Weekend Live Classes, Mentorship from our Experts, Unlimited Mock Tests and Personalized Analysis Reports, 24x7 Doubt Chat Support,.

₹ 14000/- ₹ 4999/-
Buy Now
Knockout JEE Main May 2021

Personalized AI Tutor and Adaptive Time Table, Self Study Material, Weekend Live Classes, Mentorship from our Experts, Unlimited Mock Tests and Personalized Analysis Reports, 24x7 Doubt Chat Support,.

₹ 22999/- ₹ 9999/-
Buy Now
Knockout NEET Aug 2021

Personalized AI Tutor and Adaptive Time Table, Self Study Material, Weekend Live Classes, Mentorship from our Experts, Unlimited Mock Tests and Personalized Analysis Reports, 24x7 Doubt Chat Support,.

₹ 22999/- ₹ 9999/-
Buy Now
Boost your Preparation for JEE Main with our Foundation Course
 
Exams
Articles
Questions