Java Examples - Roll through hours & months


Advertisements


Problem Description

How to roll through hours & months?

Solution

This example shows us how to roll through months (without changing year) or hrs(without changing month or year) using roll() method of Class calender.

import java.util.*;

public class Main {
   public static void main(String[] args) throws Exception {
      Date d1 = new Date();
      Calendar cl = Calendar. getInstance();
      
      cl.setTime(d1);
      System.out.println("today is "+ d1.toString());
      
      cl. roll(Calendar.MONTH, 100);
      System.out.println("date after a month will be " + cl.getTime().toString() );
      
      cl. roll(Calendar.HOUR, 70);
      System.out.println("date after 7 hrs will be "+ cl.getTime().toString() );
   }
}

Result

The above code sample will produce the following result.

today is Mon Jun 22 02:44:36 IST 2009
date after a month will be Thu Oct 22 02:44:36 IST 2009
date after 7 hrs will be Thu Oct 22 00:44:36 IST 2009

The following is an another example of Roll month.

import java.util.Calendar;

public class CalendarExample {
   public static void main(String[] args) {
      Calendar cal = Calendar.getInstance();
		System.out.println("Time:" + cal.getTime());
		
      cal.roll(Calendar.YEAR, false);
		System.out.println("Time rolling down the year:" + cal.getTime());
		
      cal.roll(Calendar.HOUR, true);
		System.out.println("Time rolling up the hour:" + cal.getTime());
   }
}

The above code sample will produce the following result.

Time:Fri Nov 11 07:01:31 UTC 2016
Time rolling down the year:Wed Nov 11 07:01:31 UTC 2015
Time rolling up the hour:Wed Nov 11 08:01:31 UTC 2015

java_date_time.htm

Advertisements