使用Java的GregorianCalendar实现日历功能

1 篇文章 0 订阅
1 篇文章 0 订阅

一次写成,没有优化代码。只是做个Demo而已。

 

package test.test;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarTest {

	public static void main(String[] args) {
		
		GregorianCalendar getDate = new GregorianCalendar();
		getDate.set(Calendar.MONTH, 1);
		int month = getDate.get(Calendar.MONTH);
		
		System.out.print("日" + "\t");
		System.out.print("月" + "\t");
		System.out.print("火" + "\t");
		System.out.print("水" + "\t");
		System.out.print("木" + "\t");
		System.out.print("金" + "\t");
		System.out.print("土" + "\t");
		
		System.out.println();
		
		int nextMonth = month;
		int i = 1;
		while(true) {
			getDate.set(Calendar.DAY_OF_MONTH, i);
			nextMonth = getDate.get(Calendar.MONTH);
			if (month != nextMonth) {
				break;
			}
			i++;
			int weekNum = getDate.get(Calendar.DAY_OF_WEEK);
			
			if (getDate.get(Calendar.DAY_OF_MONTH) == 1) {
				for (int j = 1; j < getDate.get(Calendar.DAY_OF_WEEK); j++) {
					System.out.print("\t");
				}
				System.out.print(getDate.get(Calendar.DAY_OF_MONTH) + "\t");
			} else {
				System.out.print(getDate.get(Calendar.DAY_OF_MONTH) + "\t");
			}
			
			if (weekNum == 7) {
				System.out.println();
			}
		}
	}
}

 

以下是显示结果(2012年2月):

日    月    火    水    木    金    土   
                        1     2     3     4   
5     6     7     8     9     10   11   
12   13   14   15   16   17   18   
19   20   21   22   23   24   25   
26   27   28   29   

 

(注意:Calendar里的月份是从0~11,所有将月赋值为1的时候表示的是2月份。

         星期是从1~7,天也是从1开始的

方法add(Calendar.DAY_OF_MONTH, -2)表示今天的之前第二天。

getDate.set(Calendar.DAY_OF_MONTH, i);  可以用getDate.add( Calendar.DAY_OF_MONTH , 1)代替 )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值