码迷,mamicode.com
首页 > 其他好文 > 详细

使用Calendar 将当月日历打印出来

时间:2015-04-17 13:37:26      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

package com.date;

import java.text.DateFormatSymbols;
import java.util.Calendar;

import org.junit.Test;

public class CalendarTest {
    /**
     * 打印当前月的日历
     */
    @Test
    public void test1(){
        
//        GregorianCalendar d = new GregorianCalendar();
        Calendar d = Calendar.getInstance();
        // 获取 当前   日 和月 
        int today = d.get(Calendar.DAY_OF_MONTH);
        int month = d.get(Calendar.MONTH);
        
//        System.out.println(day+"\n"+month);
        
        //设置当前时间为 本月第一天
        d.set(Calendar.DAY_OF_MONTH, 1);
        //获取这一天是星期几
        int weekday = d.get(Calendar.DAY_OF_WEEK);
        
        //获取当前地区 一周的第一天是星期几
        int firstDayOfWeek = d.getFirstDayOfWeek();
        
//        System.out.println(weekday+"\n"+firstDayOfWeek);
        
        //补充当前月 第一个星期中的 缩进的天数
        int indent =0;
        while(weekday!=firstDayOfWeek){
            indent ++;
            d.add(Calendar.DAY_OF_MONTH, -1);
            weekday = d.get(Calendar.DAY_OF_WEEK);
        }
        
        //打印星期
        String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
//        System.out.println(Arrays.asList(weekdayNames).toString());
        do{
            System.out.printf("%4s",weekdayNames[weekday]);
            d.add(Calendar.DAY_OF_MONTH, 1);
            weekday = d.get(Calendar.DAY_OF_WEEK);
        }while(weekday!=firstDayOfWeek);
        
        System.out.println();
        
        //将第一行 缩进的星期 空出来
        for(int i=0;i<indent;i++){
            System.out.print("    ");
        }
        d.set(Calendar.DAY_OF_MONTH, 1);
        
        do{
            // 打印 天
            int day = d.get(Calendar.DAY_OF_MONTH);
            System.out.printf("%3d",day);
            
            //标记当前  天
            if(day == today){
                System.out.print("*");
            }else{
                System.out.print(" ");
            }
            
            //继续下一天
            d.add(Calendar.DAY_OF_MONTH, 1);
            weekday = d.get(Calendar.DAY_OF_WEEK);
            
            //遇到 星期开始 ,换行
            if(weekday==firstDayOfWeek) System.out.println();
            
            
        }while(d.get(Calendar.MONTH) == month);
        
    }
}

结果:

  技术分享

 

使用Calendar 将当月日历打印出来

标签:

原文地址:http://www.cnblogs.com/a198720/p/4434429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!