java 用Calendar、Date类实现当前月份日历的显示

用Calendar、Date类实现当前月份日历的显示

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

public class CalendarDemo{
     public static void main(String[] args){
          Calendar cal = Calendar.getInstance();
          cal.setTime(new Date());//set date at current date
          
          int year = cal.get(Calendar.YEAR);//get year
          int month = cal.get(Calendar.MONTH)+1;//get month,because the return value of cal.get() 
                                          //is between 0-11,so the real month needs to add 1  
          //get how many days in current month
          int daysOfMonth = cal.getActualMaximum(cal.DAY_OF_MONTH);     

          cal.set(cal.DAY_OF_MONTH,1); //set date to the first day of current month
          int index = cal.get(cal.DAY_OF_WEEK)-1; //sign how many blanks befor the first day
          String[] title = {"Sun","Mon", "Tues","Wed", "Thur", "Fri", "Sat"};//the us custom
          int day = 1;  //the first day's number
          int[][] daysArray = new int[6][7];  //store the days of month        
          int mark = 0; //sign blanks 
                   
          //fill the days into daysArray
          for(int i = 0; i < 6; i++){
                for(int j = 0; j < 7; j++){
                     if( mark < index){
                          daysArray[i][j] = 0;
                          mark++;
                     }else{
                          daysArray[i][j] = day;
                          day++;
                     }
                     if(day > daysOfMonth){
                          break;
                     }
                 }
           }
           
           //present the day of month
           System.out.println("Year "+ year +"  Month " + month);
           System.out.println("------------------------------------------------------");
           for(String s : title){
                 System.out.print(s + "\t");
           }
           System.out.println();
           mark = 0;
           for(int i = 0; i < 6; i++){
                 for(int j = 0; j < 7;j++){
                     if(mark <daysOfMonth && daysArray[i][j] == 0){
                           System.out.print("  " + "\t");
                     }else if(mark < daysOfMonth && daysArray[i][j] != 0){
                           System.out.print(daysArray[i][j] +"\t");
                           mark++;
                     }else{
                           break;
                     }
                 }
                 System.out.println();
           }

      }
}

运行结果如下图:
运行结果

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值