欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java实现日历

程序员文章站 2022-05-07 21:54:52
...

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

//日历测试
public class CalenderTest {

	public static void main(String[] args) {
		//声明并创建日历对象
		GregorianCalendar calendar = new GregorianCalendar();
		
		//获取  日 月 
		int today = calendar.get(Calendar.DAY_OF_MONTH);
		
		int month = calendar.get(Calendar.MONTH);
		
		//将calendar设置这个月的第一天
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		
		//获取
		int weekday = calendar.get(Calendar.DAY_OF_WEEK);
		
		//获取一周的起始日期
		int firstDayOfWeek = calendar.getFirstDayOfWeek();
		
		int indent = 0 ;
		
		while (weekday != firstDayOfWeek) {
			indent++ ;
			calendar.add(Calendar.DAY_OF_MONTH, -1);
			weekday = calendar.get(Calendar.DAY_OF_WEEK);
			
		}
		
		//打印这周的名称
		String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
		
		do {
			System.out.printf("%4s",weekdayNames[weekday]);
			
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			
			weekday = calendar.get(Calendar.DAY_OF_WEEK);
			
		} while (weekday != firstDayOfWeek);
		
		System.out.println();
		
		for (int i = 0; i <= indent ; i++) {
			System.out.print("    ");
		}
		
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		
		do {
			//打印 天
			int day = calendar.get(Calendar.DAY_OF_MONTH);
			System.out.printf("%3d",day);
			
			if (day == today) {
				System.out.print("*");
			}else {
				System.out.print("  ");
			}
			
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			
			weekday = calendar.get(Calendar.DAY_OF_WEEK);
			
			if (weekday == firstDayOfWeek) {
				System.out.println();
			}
		} while (calendar.get(Calendar.MONTH) == month);
		
		if (weekday == firstDayOfWeek) {
			System.out.println();
		}
		
	}
}

 

相关标签: java 日历