Java Program to Show Time By Rolling Through Hours and Months


The credibility of an efficient coding language depends upon how well it can manage the date and time. In a Java Virtual Environment we get some inbuilt facilities like date, time and calendar to handle the problem related to date and time.

  • java. until date class - In Java, there are many contains those are very important for the program. Date class deals with the operation about the date and time. They are those type of classes which comes with the feature of cloneable, Serializable and comparable interfaces.

  • Extract the current date and time - There are two types of techniques to extract the current date and time using Java.

    • Implementation of date class

    • Implementation of calendar class

In the method of date class, first we will consider a string contains with date. By using this we will get the date and time as output. And by declaring a calendar class we will create an instance class to get the current time of the system by calling getTime().

Here in this article today, we will build some Java codes to show Time by Rolling through Hours and Months.

Algorithm to show time by rolling through hours and months

Here in this possible algorithm, we tried to demonstrate how to Show Time by Rolling through Hours and Months by using Java.

  • Step 1 − Start.

  • Step 2 − Declare the function for the days in year and month.

  • Step 3 − Declare, int total =0.

  • Step 4 − i<year?

  • Step 5 − If, the condition satisfied then check for a leap year with isLeapYear(i)?

  • Step 6 − Else, int i= 1. And check i<month?

  • Step 7 − If the fifth condition satisfied then; total = total+366; or, total = total+365.

  • Step 8 − Go for i++ iteration.

  • Step 9 − If the seventh condition is satisfied.

  • Step 10 − Then, total=total+getNumberOfDaysInMonth(year,i);.

  • Step 11 − Go for i++ iteration.

  • Step 12 − If not, return total.

  • Step 13 − Terminate.

Syntax to show time by rolling through hours and months

General Syntax:
public abstract void roll(int calendar_field, boolean up_down)

Using Date class:
package com.DataFlair.DateAndTime;
import java.util.Date;
public class CurrDateUsingDateClass{
   public static void main(String args[]) {
      Date date = new Date();
      System.out.println(date.toString());
   }
}
Using Calendar Class:
package com.DataFlair.DateAndTime;
import java.util.Calendar;
public class CurrDateUsingCalenderClass{
   public static void main(String args[]) {
      Calendar current = Calendar.getInstance();
      System.out.println(current.getTime());
   }
}

Above, we mentioned the possible syntaxes of the given problem. By following these syntaxes we will code some programs to get the time as a result by rolling through hours and months.

Approach

  • Approach 1 − Java Program to Show Time By Rolling Through Hours and Months

Java Program to Show Time by Rolling Through Hours and Months

In these Java build codes, we tried to explain how to apply the above algorithm and syntaxes to Show Time by Rolling through Hours and Months.

Example 1

import java.util.Calendar;
import java.util.Date;

public class Calendarof2023 {
	public static void main(String[] args) throws Exception{
      Date d1 = new Date();
      Calendar c1 = Calendar.getInstance();
      Calendar c2 = Calendar.getInstance();
      c1.setTime(d1);
      c2.setTime(d1);
      System.out.println("Today the date is " + d1.toString());
      c1.roll(Calendar.MONTH, 50);
      System.out.println("Date after rolling by 50 over month will be "+ c1.getTime().toString());
      c1.roll(Calendar.HOUR, 70);
      System.out.println("Date after rolling by 70 over hours will be "+ c1.getTime().toString());
      c1.roll(Calendar.YEAR, 2);
      System.out.println("Date after rolling by 2 over year is "+ c1.getTime().toString());
      c2.roll(Calendar.MONTH, false);
      System.out.println("Date after false rolling over month will be "+ c2.getTime().toString());
      c2.roll(Calendar.HOUR, true);
      System.out.println("Date after true rolling over hour will be "+ c2.getTime().toString());
      c2.roll(Calendar.YEAR, true);
      System.out.println("Date after true rolling over year is "+ c2.getTime().toString());
	}
}

Output

Today the date is Mon Apr 10 10:42:31 GMT 2023
Date after rolling by 50 over month will be Sat Jun 10 10:42:31 GMT 2023
Date after rolling by 70 over hours will be Sat Jun 10 08:42:31 GMT 2023
Date after rolling by 2 over year is Tue Jun 10 08:42:31 GMT 2025
Date after false rolling over month will be Fri Mar 10 10:42:31 GMT 2023
Date after true rolling over hour will be Fri Mar 10 11:42:31 GMT 2023
Date after true rolling over year is Sun Mar 10 11:42:31 GMT 2024

Example 2

import java.util.*;
public class Calendar2023 {
	public static void main(String args[]){
      Calendar calndr = Calendar.getInstance();
      System.out.println("The Current Month of the year"+ calndr.get(Calendar.MONTH));
      calndr.roll(Calendar.MONTH, true);
      System.out.println("The New Month is from the year: "+ calndr.get(Calendar.MONTH));
      calndr.roll(Calendar.MONTH, false);

      // Displaying the result after operation
      System.out.println("The new month is: "+ calndr.get(Calendar.MONTH));
	}
}

Output

The Current Month of the year3
The New Month is from the year: 4
The new month is: 3

Example 3

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 the date - @ "+ d1.toString());
      
      cl. roll(Calendar.MONTH, 100);
      System.out.println("date after a month will be as per the calculation - > " + cl.getTime().toString() );
      
      cl. roll(Calendar.HOUR, 70);
      System.out.println("date after 7 hrs will be today is ->> "+ cl.getTime().toString() );
   }
}

Output

today is the date - @ Mon Apr 10 10:44:41 GMT 2023
date after a month will be as per the calculation - > Thu Aug 10 10:44:41 GMT 2023
date after 7 hrs will be today is ->> Thu Aug 10 08:44:41 GMT 2023

Example 4

import java.util.Calendar;

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

Output

Time is ----- >>:Mon Apr 10 10:45:26 GMT 2023
Time rolling down the year, result is here--->>:Sun Apr 10 10:45:26 GMT 2022
Time rolling up the hour is now ---->>>:Sun Apr 10 11:45:26 GMT 2022

Example 5

import java.util.*;
 
public class GetCurrentDateAndTime2023{
   public static void main(String args[]){
      int day, month, year;
      int second, minute, hour;
      GregorianCalendar date = new GregorianCalendar();
 
      day = date.get(Calendar.DAY_OF_MONTH);
      month = date.get(Calendar.MONTH);
      year = date.get(Calendar.YEAR);
 
      second = date.get(Calendar.SECOND);
      minute = date.get(Calendar.MINUTE);
      hour = date.get(Calendar.HOUR);
 
      System.out.println("Current date is now --->>  "+day+"/"+(month+1)+"/"+year);
      System.out.println("Current time is now --->> "+hour+" : "+minute+" : "+second);
   }
}

Output

Current date is now --->>  10/4/2023
Current time is now --->> 10 : 46 : 24

Example 6

package com.DataFlair.DateAndTime;
import java.util.*;
import java.text.*;
public class DateFormatting{
   public static void main(String args[]) {
      Date CurrDate = new Date( );
      SimpleDateFormat formatDate = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
      System.out.println("Current Date(Formatted) Like This:---> " + formatDate.format(CurrDate));
   }
}

Output

Current Date(Formatted) Like This:---> Mon 2023.04.10 at 10:47:17 AM GM

Example 7

import java.util.Scanner;
public class Tptimedateexample {
 
   public static void main(String[] args) {
      long totalMilliseconds = System.currentTimeMillis();
      long totalSeconds = totalMilliseconds / 1000;
      long currentSecond = (int)(totalSeconds % 60);
      long totalMinutes = totalSeconds / 60;
      long currentMinute = (int)(totalMinutes % 60);
      long totalHours = totalMinutes / 60;
      long currentHour = (int)(totalHours % 24);
      long totalDays = totalHours / 24;
      int currentYear = (int)(totalDays / 365) + 1970;
      long daysInCurrentYear = (totalDays - numberOfLeapYearsSince1970(currentYear)) % 365;
      if (currentHour > 0) daysInCurrentYear++; 
      int currentMonthNum = getMonthFromDays(currentYear, (int) daysInCurrentYear);
      String month = getMonthName(currentMonthNum);
      int daysTillCurrentMonth = getNumOfDaysToReachThatMonth(currentYear, currentMonthNum);

      int startDay = getStartDay(currentYear, currentMonthNum);
      int today = (int) daysInCurrentYear - daysTillCurrentMonth;
      String dayOfWeek = dayNameOfWeek( ((startDay + today) % 7));
      System.out.println("Current date and time is here. Note That---->>>>: " + dayOfWeek + " " + month + " " + today +", " + currentYear +" " + currentHour + ":"+ currentMinute + ":" + currentSecond );

   }

   public static String dayNameOfWeek(int dayOfWeek) {

      switch (dayOfWeek) {
         case 2: return "Monday";
         case 3: return "Tuesday";
         case 4: return "Wednesday";
         case 5: return "Thursday";
         case 6: return "Friday";
         case 7: return "Saturday";
         case 1: return "Sunday";
         default: return null;
      }
   }

   public static int numberOfLeapYearsSince1970(long year) {

      int count = 0;
      for (int i = 1970; i <= year; i++) {
         if (isLeapYear(i))count++;
      }
      return count;
   }


   public static int getMonthFromDays(int year, int days) {
      int dayTracker = 0;
      for (int i = 1; i <= 12; i++) {

         dayTracker += getNumberOfDaysInMonth(year, i);

         if (dayTracker > days) return i;
      }
      return 12;
   }

   public static int getNumOfDaysToReachThatMonth(int year, int month) {
      int dayTracker = 0;
      for (int i = 1; i < month; i++) {
         dayTracker += getNumberOfDaysInMonth(year, i);
      }
      return dayTracker;
   }
    public static int getStartDay(int year, int month) {
      final int START_DAY_FOR_JAN_1_1800 = 3;
      int totalNumberOfDays = getTotalNumberOfDays(year, month);
      return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7;
   }
   public static int getTotalNumberOfDays(int year, int month) {
      int total = 0;
      for (int i = 1800; i < year; i++)
         if (isLeapYear(i))
            total = total + 366;
         else
            total = total + 365;
      for (int i = 1; i < month; i++)
      total = total + getNumberOfDaysInMonth(year, i);

      return total;
   }
   public static int getNumberOfDaysInMonth(int year, int month) {

      if (month == 1 || month == 3 || month == 5 || month == 7 ||
                month == 8 || month == 10 || month == 12)
            return 31;

        if (month == 4 || month == 6 || month == 9 || month == 11)
            return 30;

        if (month == 2) return isLeapYear(year) ? 29 : 28;

      return 0; 
   }
   public static boolean isLeapYear(int year) {
      return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
   }
   public static String getMonthName(int month) {
      String monthName = "";
      switch (month) {
         case 1: monthName = "January"; break;
         case 2: monthName = "February"; break;
         case 3: monthName = "March"; break;
         case 4: monthName = "April"; break;
         case 5: monthName = "May"; break;
         case 6: monthName = "June"; break;
         case 7: monthName = "July"; break;
         case 8: monthName = "August"; break;
         case 9: monthName = "September"; break;
         case 10: monthName = "October"; break;
         case 11: monthName = "November"; break;
         case 12: monthName = "December";
      }

      return monthName;
   }

}

Output

Current date and time is here. Note That---->>>>: Monday April 10, 2023 10:54:30

Conclusion

Here, we have learnt about the time rolling methods with some possible java codes by following the syntaxes and algorithm. Hope this article helped you to understand the modus operandi of the various rolling methods mentioned here by which we have slolved this problem.

Updated on: 12-Apr-2023

47 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements