Java Program to Show Time By Rolling Through Hours and Months
Java.util package has a Calendar class which has some predefined methods, which helps us to do some operations related to date and time. Calendar class has a predefined method called roll() method, with the help of which we can roll through months (without changing the year) and hours(without changing the month and year).
Rolling basically means that getting back over the same state after a certain period. For eg, let’s consider that it is the month of October, and we have rolled over the month by 50, it means that we have rolled by 2 months, ie (50%12=2), since there is a total of 12 months in a year, so current month after rolling by 50 months would be December.
Consider another example that let’s say we have rolled over hours by the amount 76 and current status of time is 5:00 pm and date is 22 October 2020, so after we have rolled for 76 hours, the status of time will be 9:00 pm and data will be 22 October 2020, it is so because there is a total of 24 hours in a day and (76%24=4), so the current time status will only be increased by 4.
public abstract void roll(int calendar_field, boolean up_down)
Here, roll() method takes 2 parameters calendar_field and up_down.
- calendar_field: It is the hour or month or year on which we want to roll
- up_down: It is the amount by which we have to roll, which is either a boolean value or an integer value. In the above examples, it is shown that how to roll for an integer value (it can be either both positive or a negative value), but for a boolean value, if the value is passed is true, it means that we have to roll by +1 amount and if the value passed is false, it means that roll by -1 amount.
Example: The below example explains how to use the roll() method programmatically.
Today is Fri Oct 30 06:19:15 UTC 2020 Date after rolling by 50 over month will be Wed Dec 30 06:19:15 UTC 2020 Date after rolling by 70 over hours will be Wed Dec 30 04:19:15 UTC 2020 Date after rolling by 2 over year is Fri Dec 30 04:19:15 UTC 2022 Date after false rolling over month will be Wed Sep 30 06:19:15 UTC 2020 Date after true rolling over hour will be Wed Sep 30 07:19:15 UTC 2020 Date after true rolling over year is Thu Sep 30 07:19:15 UTC 2021
The Current Month is: 9 The New Month is: 10 The new month is: 9
Please Login to comment...