Java implementation million Calendar summary _java

Source: Internet
Author: User
Tags current time

One, Java implements the code for the calendar:

Package calendar; Import java.util.scanner;//Calendar items public class rili{public static void Main (string[] args) {Scanner a=new Scanner (System.
 in);
 System.out.println ("Please enter 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;
  }else{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; }}else{if (i==4| | i==6| | i==9| |
  i==11) {sum+=30;
  }else{sum+=31;
 }} sum=sum+1;
 int wekday=sum%7;
 System.out.println ("day \ t/t two \ t three t four \ t five \ t six");
 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");
  }else{System.out.print (i+ "T");
 } sum++;


 }
 }
}

Two. A Java calendar, relatively simple kind, show year, Day, week, current date is the week, display leap year, print calendar, and so on, can also show the current date is the first days of the day, the specified date is the day of the week, using the Kimlarsson calculation formula, w= (d+2*m+3* (m+1)/5+ y+y/4-y/100+y/400) MoD 7, in which D represents the number of days in the date, m represents the number of months, and Y represents the number of years. Note: There is a different formula in the formula: January and February are considered as the January or March and January or April of the previous year, for example: if it is 2004-1-10, the conversion is: 2003-13-10 to substitute the formula.

public class MyCalendar {//The following program segment is used to calculate the public static int cptday (int years, int month, int day) for the first days of the year in which the date is entered.  Yte dayadd[]={1,-2,1,0,1,0,1,1,0,1,0,1};  The difference int daycount = 0 used to store the number of days per month and 30;

      This is the number of days Daycount counter, initialized to 0 for (int i=0; i<month-1; i++) daycount+= (30+dayadd[i));

      Daycount+=day;

  Return (MONTH&GT;2) daycount+isleap (year):d Aycount; //Leap year judgment Program segment, Leap year returns 1, excepting returns 0 public static int isleap (int years) {if (year%400==0) | |

      ((year%4==0) && (year%100!=0))

    return 1;

  return 0;

  //Calculation input date is the day of the Week//using the Kimlarsson 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 number of days in the date, M is the number of months, and Y represents the number of years.

  Note: There is a different formula in the formula://See January and February as the January or March and January or April of the previous year, for example: if it is 2004-1-10, the conversion is: 2003-13-10 to substitute the formula.

    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 program segment is to calculate the public static int weekcount for the first weeks of the year by entering a date (iNT Year,int Month,int day) {int daycnt = Cptday (Year,month,day);

    int weekminus = Getweek (year,month,day)-getweek (year,1,1);

    int weekcnt = 0;

    if (daycnt%7==0) weekcnt = daycnt/7+ ((weekminus>0)? 1:0);

    else weekcnt = daycnt/7+ ((weekminus>0)? 2:1);  

  return weekcnt; }//print perpetual public static void printcal (int years) {byte dayadd[]={0,1,-2,1,0,1,0,1,1,0,1,0,1};//The same, the number of days per month and the difference of 30, note      Italy, Dadadd[0] 0 does not use to int wkpoint = Getweek (year,1,1);                 Wkpoint is used to indicate the current date of the number of weeks int t = 0;                 T is used as a marker, resolving leap year February has 29 days of problem int bk = 0;

    BK is used to record the number of blanks needed to be lost 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;

      When and only when the leap year of February will be placed to 1 System.out.println ("\n\n\t\t" +year+ "Years" +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"); Cycle output Monthly Date if (wkpoint==6) {wkpoint = 0; System.out.print (' \ n ');}                       

      When the Wkpoint counter is 6 o'clock, it is set to 0 and the newline else is wkpoint++;

    }} public static void Main (string[] args) {String week[]={"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

    System.out.println ("The date entered is the +cptday of the Year" (2009,2,15) + "Days");

    SYSTEM.OUT.PRINTLN ("This day is the first of the Year" +weekcount (2009,2,15) + "Zhou" +week[getweek (2009,2,15)));

  Printcal (2009);
 }

}

Three

1. The user enters the information--> to carry on the information judgment (whether meets the request)

2. Based on January 1, 1900 (Monday), calculates the total number of days from January 1, 1900 to the day
(1) First calculate the total number of days from 1900 to (user input of year-1)--> Note the points of the flat leap years
(2) Calculate the number of days that the user enters the year from January to (user enters month-1)

3. Calculate the first day of the input month is the week

4. Formatted output

Let's follow step-by-step code to resolve the following steps

A), use Do-while loop to accept user input information, and use IF-ELSE statement to judge

int year;  
int month;  
Boolean xn = false; 
do {  
      System.out.println ("Enter year:");  
      Year = Input.nextint ();  
      System.out.println ("Please enter the month:");  
      month = Input.nextint ();  
      Judgement of input information using Boolean expressions  
      xn = (Month < 1) | | (Month > 12) | | (Year < 1);  
      if (xn)  
     {  
         System.out.println ("Input information error, please re-enter!") ");  
     }  
} while (xn); 

Second, judge the level leap year and calculate the total number of days from 1900 to (user input: 1)

int everyyearday = 0; Number of days per year  
int totalyearsdays = 0;//number of days of year  
int inputyearday = 0  //number of days of user input year  
boolean yn = false;  Identify flat leap years  
 
//use for loops to count days for  
(int i = 1900;i < =year;i + +)  
{  
   if (((i% 4 = 0) && (i% 100!= 0)) | | (i% 400 = 0)) The judgment condition of leap year  
   {  
          yn = true;  
          Everyyearday = 366;  
   }  
   else 
  {  
          yn = false;  
          Everyyearday = 365;  
  }  
  If the year in the loop is less than the year entered by the user, the cumulative number of days if  
 (i < year)  
   {  
       totalyearsdays = totalyearsdays + everyyearday;  
   }  
   else 
   {  
       inputyearday = everyyearday;  
       SYSTEM.OUT.PRINTLN (Year + "total:" + Inputyearday + "Day");  
   }  
 

Third, determine the number of days of the month, and calculate the year January to (user input month-1) days

int everymonthday = 0;  Record the number of days per month  
int totalmonthsdays = 0;//Total days  
int inputmonthday = 0;  Record the number of months entered by the user in the days of the user input year  
 
//use for loop to count days for  
(int i = 1;i <= month;i + +)  
{  
   switch (i)  
   {case  
       4: C11/>case 6: Case  
       9: Case one  
       :  
            everymonthday =;  
            break;  
       Case 2:  
            if (xn)  //xn is a Boolean variable  
            {  
               everymonthday =  
            , used to record a leap year) else 
           {  
               everymonthday =;  
           }  
           break;  
       Default:  
                Everymonthday =;  
                break;  
   if (i < month)  
  {  
       totalmonthsdays = totalmonthsdays + everymonthday;  
  }  
  else 
  {  
        inputmonthday = everymonthday;  
        SYSTEM.OUT.PRINTLN (month + "Month Total:" + Inputmonthday + "Day");  
  }  
 

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

int total = totalmonthsdays + totalyearsdays; Calculate Total Days
int temp = (total + 1)% 7; Determine how many days of the first day of the month you enter

V), formatted output

Because our input format is  
//Sunday Monday Tuesday Wednesday Thursday Friday Saturday  
//When Sunday, we will output directly, but when  
//First day is Monday, we must first print out the space  
// And then output the date to allow the number and week to correspond  
//Print space for  
(int spaceno = 0;spaceno < Temp;spaceno + +)  
{  
   System.out.print ("T" );  
}  
 
Print number in order  
for (int i = 1;i <= inputmonthday;i + +)  
{if (total  
   + i)% 7)   //Determine if the line should be changed  
   {  
        Sy Stem.out.println (i);  
   }  
   else 
  {  
         System.out.print (i + "/t");  
  }  
 

 

 

Four, Java (with the Calendar class) to write a calendar, enter the year and display calendars of the year

public class MyCalendar {public static void main (String args[]) {Scanner sc = new Scanner (system.in);
    Calendar C = calendar.getinstance ();
    System.out.println ("Please enter the number of years: (for example 2014)");
    int year = Sc.nextint ();
Sc.close ();
    int year = 2014;
     
     
    C.set (calendar.year,year); for (int i = 0; i < i++) {C.set (calendar.month,i);//C.set (calendar.date,1);//set to January Printmonth
    (c);  } public static void Printmonth (Calendar c) {c.set (calendar.day_of_month,1);
    Set into a day System.out.printf ("\n\n=========%s month =========\n", C.get (Calendar.month) +1);
    String[] weeks = {"Day", "one", "two", "three", "four", "five", "six"}; 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); WhileC.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); }
  }
}

V. Procedure: Calendar + Clock Small program realization

Java knowledge points are: Java Common Necoux and tools (Date class, Calendar class, etc.), exceptions (Try.....catch), threading, 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 Almanac class MainFrame extends jframe{JPanel panel=new JPanel (New BorderLayout ());//borderlayout for border layout JPanel panel1=
New JPanel ();
JPanel panel2=new JPanel (New GridLayout (7,7));//gridlayout for grid layout JPanel panel3=new ();
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 (); Instantiates calendar MainFrame () {super ("perpetual-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);//sets the displayed character to center Panel2.add (label);
Panel3.add (This) (new Clock);
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 ()); Gets the currently selected year C_month=integer.parseint (Com2.getselecteditem (). toString ())-1; Get the current month, and subtract 1, the month of the computer is 0-11 c_week=use (c_year,c_month); Call the function use, get the week resetday (C_week,c_year,c_month);
Call function Resetday}});
Setcontentpane (panel);
SetVisible (TRUE);
Setresizable (FALSE);
public void Init () {int year,month_num,first_day_num;
String log[]={"Day", "one", "two", "three", "four", "five", "six"}; for (int i=0;i<7;i++) {label.settext (log);T i=0;i<49;i=i+7) {label.setforeground (color.red);//Set Sunday date to red} for (int i=6;i<49;i=i+7) {
Label.setforeground (color.red);//The Saturday date is also set 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)); Gets the current time of the month year= (int) (Now.get (calendar.year)); The year Com1.setselectedindex (year-1) to get the current time; Sets the Drop-down list to display as the current year com2.setselectedindex (Month_num);
The Set Drop-down list is displayed as 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 as the first day of the year to query week_num= (int) (now
. Get (Calendar.day_of_week));/Gets the first day of the week return week_num; The public void resetday (int week_log,int year_log,int month_log) {int month_score_log;//To determine if it is a leap year mark int month_day_score;
The number of days in which the month is stored 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) {//Judge whether it is a leap year month_score_log=1;} month_log=month_log+1; //The number of months to be sent plus 1 switch (month_log) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:month_day_score=31; 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;
for (int i=7;i<49;i++) {//Initialize label Label.settext ("");} week_log=week_log+6;
Add the week number to 6 to make the display correct 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 ();// Call thread} public void Run () {while (true) {try{t.sleep (1000);//hibernate 1 seconds}catch (interruptedexception e) {System.out.println ("exception
");
}
This.repaint (100); 
} public void Paint (Graphics g) {font f=new font ("Arial", font.bold,16); SimpleDateFormat sdf=new SimpleDateFormat ("yyyy ' Year ' MM ' month ' dd ' Day ' HH:mm:ss ')"//Format time displayType 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);
The public class wnl{public static void Main (String [] args) {jframe.setdefaultlookandfeeldecorated (true);
MainFrame start=new MainFrame (); } 
}

The above is the Java implementation of the calendar data, I hope to help realize the function of friends, thank you for your support of this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.