English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Summary of Java Implementation of Perpetual Calendar

1. Java code to implement an eternal calendar:

package calendar;
import java.util.Scanner;//Calendar project
public class Calendar{
 public static void main(String[] args){
 Scanner A=new Scanner(System.in);
 System.out.println("Please enter the year:");
 int year=A.nextInt();
 System.out.println("Please enter the month:");
 int month=A.nextInt();
 int sum=0;
 for(int i=1900;i<year;i++){
  if(i%4==0&&i%100!=0||i%400==0){
  sum=sum+366;
  }
  sum=sum+365;
  }
 }
 for(int i=1;i<month;i++){
  if(i==2){
  if(year%4==0&&year%100!=0||year%400==0){
   sum=sum+29;}
  else{
   sum=sum+28;
  }
  }
  if(i==4||i==6||i==9||i==11){
   sum+=30;
  }
   sum+=31;
  }
  }
 }
 sum=sum+1;
 int wekday=sum%7;
 System.out.println("Sun	Mon	Tue	Wed	Thu	Fri	Sat");
 for(int i=1;i<=wekday;i++){
  System.out.print("\t");
 }
 int f=0;
 if(month==4||month==6||month==9||month==11){
  f=30;}
 if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){f=31;}
 if(month==2){
  if(year%4==0&&year%100!=0||year%400==0){f=29;}
  else{f=28;}
 }
 for(int i=1;i<=f;i++){
  if(sum%7==6){
  System.out.print(i+"\n");
  }
  System.out.print(i+"\t");
  }
  sum++;
 }
 }
}

A simple Java calendar, displaying year, month, day, day of the week, the week of the current date, leap year, and printing the calendar, etc. It can also display the day of the year for the current date and the day of the week for a specified date. It adopts the Kim Larsen calculation formula, W = (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7 In the formula, d represents the day of the month, m represents the month number, and y represents the year number. Note: There is a difference in the formula compared to other formulas: January and February are considered as the 13th and 14th months of the previous year, for example, if it is2004-1-10Then it is converted to:2003-13-10Substitute into the formula for calculation.

public class myCalendar {
  //The following code segment is used to calculate which day of the year the input date falls on.
  public static int cptDay(int year , int month , int day){
    byte dayadd[]={1,-2,1,0,1,0,1,1,0,1,0,1};  //used to store the number of days in each month3the difference from 0
    int daycount = 0;  //This is the day count daycount counter, initialized to 0
      for(int i=0; i<month-1; i++)
        daycount+=(30+dayadd[i]);
      daycount+=day;
      return (month>2)?daycount+isLeap(year):daycount;
  }
  //Leap year determination program segment, returning10, returning 0 for a common year
  public static int isLeap(int year){
    if((year%400==0)||((year%4==0)&&(year%100!=0)))
      return 1;
    return 0;
  }
  //to calculate which day of the week the input date is
  //This uses the Kimball-Rosenberg calculation formula
  //W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7
  //In the formula, d represents the day of the month, m represents the month number, and y represents the year number.
  //Note: There is a difference in the formula compared to other formulas:
  //January and February are considered as the 13th and 14th months of the previous year, for example, if it is2004-1-10Then it is converted to:2003-13-10Substitute into the formula for calculation.
  public static int getWeek(int year, int month, int day){
    if(month<3)
    { month+=12; year--;}
    return (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400)%7;
  }
  //The following code segment is used to calculate which week of the year the input date falls on.
  public static int weekCount(int year, int month, int day){
    int dayCnt = cptDay(year, month, day);
    int weekminus = getWeek(year, month, day);-getWeek(year,1,1);
    getWeek(year,
    int weekCnt = 0;7if(dayCnt%/7+((weekminus>0)&63;1:0);
    else weekCnt = dayCnt/7+((weekminus>0)&63;2:1);
    return weekCnt;  
  }
  //Print the万年历
  public static void printCal(int year){
    byte dayadd[]={0,1,-2,1,0,1,0,1,1,0,1,0,1}; //Similarly, the number of days in each month and3the difference from 0, note that the 0 of dadadd[0] is not used
    int wkpoint = getWeek(year,1,1);      //wkpoint is used to indicate the weekday number of the current date   
    int t = 0;                 //t is used as a marker to solve the problem of leap years2month has29the issue of days in the month
    int bk = 0;                 //bk is used to record the number of spaces to be entered
    String week[]={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
    for(int i=1;i<13;i++)
    {
      t = 0;
      bk = 0;
      if((i==2)&&((isLeap(year))==1))
        t = 1;               //only when it is a leap year2months will be set to1
      System.out.println("\n\n\t\t"+year+" Year "+i+" Month\n");
      for(int j=0;j<7;j++)
        System.out.print(week[j]+"\t");
      System.out.println();
      while(bk++<wkpoint)
        System.out.print('\t');
      for(int j=1;j<=(30+dayadd[i]+t);j++)
      {
        System.out.print(j+"\t");      //Loop to output the dates of each month
        if(wkpoint==6)
          { wkpoint = 0; System.out.print('
');} //when the wkpoint counter is6set it to 0 and then go to a new line
        else
          wkpoint++;                       
      }
    }
  }
  public static void main(String[] args){
    String week[]={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
    System.out.println("The entered date is the "+cptDay(2009,2,15)+"day");
    System.out.println("This day is the "+weekCount(2009,2,15)+"Week "+week[getWeek(2009,2,15);
    printCal(2009);
  }
}

3)

 1.User input information-->for information judgment (whether it meets the requirements)

2.With1900 year1Month1day (Monday) as a reference, calculate1900 year1Month1days to the current day
   (1) first calculate1900 to (the year entered by the user - 1) total days   -->Note the difference between leap years and common years
   (2) to calculate the total number of days for the year entered by the user1Month to (the month entered by the user - 1number of days)

 3.Calculate the day of the week for the first day of the month entered by the user

4.Formatted output

Below, we will step by step parse the code

1) Use do-while loop to accept user input information and use if-else statement for judgment

int year;  
int month;  
boolean xn = false;  
do 
{  
      System.out.println("Please enter the year:");  
      year = input.nextInt();  
      System.out.println("Please enter the month:");  
      month = input.nextInt();  
      //Use boolean expressions to judge input information  
      xn = (month < 1) || (month > 12) || (year < 1);  
      if(xn)  
     {  
         System.out.println("Input information error, please enter again!");  
     }  
}while(xn); 

2) Determine whether it is a leap year and calculate1900 to (the year entered by the user - 1Total number of days from 00 to (the year entered by the user

int everyYearDay = 0; //Number of days in each year  
int totalYearsDays = 0; //Calculate the number of days in the year  
int inputYearDay = 0  //Record the number of days in the year entered by the user  
boolean yn = false;  //Identify whether it is a leap year  
//Use a for loop to calculate the number of days  
for(int i = 1900; i <= year; i ++)  
{  
   if(((i % 4 == 0)&&(i % 100 != 0))||(i % 400 == 0)) //The judgment condition for leap years  
   {  
          yn = true;  
          everyYearDay = 366;  
   }  
   else 
  {  
          yn = false;  
          everyYearDay = 365;  
  }  
  //Accumulate the number of days if the year in the loop is less than the year entered by the user  
 if(i < year)  
   {  
       totalYearsDays = totalYearsDays + everyYearDay;  
   }  
   else 
   {  
       inputYearDay = everyYearDay;  
       System.out.println(year + "Year has:" + inputYearDay + "day");  
   }  
} 

3) Determine the number of days in the month and calculate the total number of days in the current year1Month to (the month entered by the user -1number of days)

int everyMonthDay = 0;  //Record the number of days in each month  
int totalMonthsDays = 0; //Total number of days  
int inputMonthDay = 0;  //Record the number of days in the month entered by the user in the year entered by the user  
//Use a for loop to calculate the number of days  
for(int i = 1;i <= month;i ++)  
{  
   switch(i)  
   {  
       case 4:  
       case 6:  
       case 9:  
       case 11:  
            everyMonthDay = 30;  
            break;  
       case 2:  
            if(xn)  //xn is a boolean variable used to record leap years  
            {  
               everyMonthDay = 29;  
            }  
            else 
           {  
               everyMonthDay = 28;  
           }  
           break;  
       default:  
                everyMonthDay = 31;  
                break;  
   }  
   if(i < month)  
  {  
       totalMonthsDays = totalMonthsDays + everyMonthDay;  
  }  
  else 
  {  
        inputMonthDay = everyMonthDay;  
        System.out.println(month + "month has:" + inputMonthDay + "day");  
  }  
} 

Four, calculate the total number of days and calculate the day of the week of the first day of the month entered by the user

int total = totalMonthsDays + totalYearsDays; //Calculate the total number of days   
int temp = (total + 1) % 7; //Determine the day of the week of the first day of the input month 

Five, formatted output

//Because our input format is  
//Monday, Tuesday, Wednesday, Thursday, Friday, Saturday  
//When it is Sunday, we can output directly, but when  
//When the first day is Monday, we must print spaces first  
//Then output the date, so that the number and the week can correspond  
//Print spaces  
for(int spaceno = 0;spaceno < temp;spaceno ++)  
{  
   System.out.print("/t);  
}  
//Print numbers in order  
for(int i = 1;i <= inputMonthDay;i ++)  
{  
   if((total + i % 7)   //Determine whether it is time to change lines  
   {  
        System.out.println(i);  
   }  
   else 
  {  
         System.out.print(i + "/t);  
  }  
} 

Four, write a perpetual calendar using the Calendar class in Java, input the year and display the calendar of the current year

public class MyCalendar {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    Calendar c = Calendar.getInstance();
    Please enter the year number (for example 2014)"
    int year = sc.nextInt();
    sc.close();
//   int year = 2014;
    c.set(Calendar.YEAR,year);
    for (int i = 0; i < 12; i++) {
      c.set(Calendar.MONTH,i); //
      c.set(Calendar.DATE,1); //Set to1Month
      printMonth(c);
    } 
  }
  public static void printMonth(Calendar c){
    c.set(Calendar.DAY_OF_MONTH,1);  //Set to the first day
    System.out.printf("\n\n========= %s Month =========\n",c.get(Calendar.MONTH)+1);
    String[] weeks = { "Day", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    for (int i = 0; i < weeks.length; i++) {
      System.out.printf("%s" + (i != 6 ?"\t":"\n"),weeks[i]);
    }
    int offday = c.get(Calendar.DAY_OF_WEEK) - 1;
    for(int i = 0; i < offday; i++){
      System.out.printf("\t");
    }
    int month = c.get(Calendar.MONTH);
    while(c.get(Calendar.MONTH) == month ){
      System.out.printf("%d" + ( (c.get(Calendar.DAY_OF_WEEK)) != 7 ? "\t":"\n"),c.get(Calendar.DAY_OF_MONTH));
      c.add(Calendar.DAY_OF_MONTH, 1);
    }
  }
}

 5. Program: Perpetual Calendar+Clock mini program implementation

Java knowledge includes: common libraries and tools (such as Date class, Calendar class), exceptions (try...catch), threads, and AWT graphical user interface and other basic knowledge points.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
//Create window and calendar
class MainFrame extends JFrame{
JPanel panel=new JPanel(new BorderLayout());//BorderLayout is a border layout
JPanel panel1=new JPanel();
JPanel panel2=new JPanel(new GridLayout(7,7));//GridLayout is a grid layout
JPanel panel3=new JPanel();
JLabel []label=new JLabel[49];
JLabel y_label=new JLabel("Year");
JLabel m_label=new JLabel("Month");
JComboBox com1=new JComboBox();
JComboBox com2=new JComboBox();
JButton button=new JButton("View");
int re_year,re_month;
int x_size,y_size;
String year_num;
Calendar now = Calendar.getInstance(); //Instantiate Calendar
MainFrame(){
super("万年历-Jackbase");
setSize(300,350);
x_size=(int)(Toolkit.getDefaultToolkit().getScreenSize().getWidth());
y_size=(int)(Toolkit.getDefaultToolkit().getScreenSize().getHeight());
setLocation((x_size-300)/2,(y_size-350)/2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel1.add(y_label);
panel1.add(com1);
panel1.add(m_label);
panel1.add(com2);
panel1.add(button);
for(int i=0;i<49;i++){
label=new JLabel("",JLabel.CENTER);//The displayed characters are centered
panel2.add(label);
}
panel3.add(new Clock(this));
panel.add(panel1,BorderLayout.NORTH);
panel.add(panel2,BorderLayout.CENTER);
panel.add(panel3,BorderLayout.SOUTH);
panel.setBackground(Color.white);
panel1.setBackground(Color.white);
panel2.setBackground(Color.white);
panel3.setBackground(Color.white);
Init();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int c_year, c_month, c_week;
c_year = Integer.parseInt(com1.getSelectedItem().toString()); //Get the current selected year
c_month = Integer.parseInt(com2.getSelectedItem().toString())-1; //Get the current month and subtract1,The month in the computer is 0-11
c_week = use(c_year, c_month); //Call the function use to get the day of the week
Resetday(c_week, c_year, c_month); //Call the function Resetday
}});
setContentPane(panel);
setVisible(true);
setResizable(false);
}
public void Init() {
int year, month_num, first_day_num;
String log[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
for(int i=0;i<7;i++){
label.setText(log);
}
for(int i=0;i<49;i=i+7){
label.setForeground(Color.red); //Set the date of Sunday to red
}
for(int i=6;i<49;i=i+7){
label.setForeground(Color.red);//Set the date of Saturday to red
}
for(int i=1;i<10000;i++){
com1.addItem(""+i);
}
for(int i=1;i<13;i++){
com2.addItem(""+i);
}
month_num = (int)(now.get(Calendar.MONTH)); //Get the current month
year = (int)(now.get(Calendar.YEAR)); //Get the current year
com1.setSelectedIndex(year-1); //Set the dropdown list to display the current year
com2.setSelectedIndex(month_num); //Set the dropdown list to display the current month
first_day_num = use(year, month_num);
Resetday(first_day_num, year, month_num);
}
public int use(int reyear,int remonth){
int week_num;
now.set(reyear,remonth,1); //Set the time to the first day of the year and month to be queried
week_num= (int)(now.get(Calendar.DAY_OF_WEEK));//Get the first day of the week
return week_num;
}
public void Resetday(int week_log,int year_log,int month_log){
int month_score_log; //Leap year judgment mark
int month_day_score; //Store the number of days in the month
int count;
month_score_log=0;
month_day_score=0;
count=1;
if(year_log%4==0&&year_log%100!=0||year_log%400==0){//Determine if it is a leap year
month_score_log=1;
}
month_log=month_log+1; //Add the received month number1
switch(month_log){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
month_day_score=31;
break;
case 4:
case 6:
case 9:
case 11:
month_day_score=30;
break;
case 2:
if(month_score_log==1){
month_day_score=29; 
}
else{
month_day_score=28;
}
break;
}
for(int i=7;i<49;i++){ //Initialize label
label.setText("");
}
week_log=week_log+6; //Add the week number6to display correctly
month_day_score=month_day_score+week_log;
for(int i=week_log;i<month_day_score;i++,count++){
label.setText(count+""
}
}
}
//Create clock
class Clock extends Canvas implements Runnable{
MainFrame mf;
Thread t;
String time;
Clock(MainFrame mf){
this.mf=mf;
setSize(400,40);
setBackground(Color.white);
t=new Thread(this); //Instantiate thread
t.start(); //Invoke thread 
}
public void run() {}}
while (true) {

t.sleep(1000); //Sleep1Seconds
}
System.out.println("Exception");
}
this.repaint(),100);
}
}
public void paint(Graphics g) {
Font f = new Font("Song", Font.BOLD,16); 
SimpleDateFormat SDF = new SimpleDateFormat("yyyy'年'MM'月'dd'日'HH:mm:ss");//Format the type of time display
Calendar now = Calendar.getInstance();
time = SDF.format(now.getTime()); //Get the current date and time
g.setFont(f);
g.setColor(Color.red);
g.drawString(time,100,25);
}
}
public class Wnl {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
MainFrame start = new MainFrame();
} 
}

That is all the information for implementing the perpetual calendar in Java. I hope it can help those who want to implement this function, thank you all for your support of this site!

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like