Core in JAVA01 GregorianCalendar 类的使用

1.日期打印

需要用到的java类

import java.util.Calendar;

import java.text.DateFormatSymbols;

import java.util.GregorianCalendar;

主要代码

GregorianCalendar gre = new GregorianCalendar();

//获得当前日期

int today = gre.get(Calendar.DAY_OF_MONTH);

//获得当前月份

int month = gre.get(Calendar.MONTH);

//设置这个月第一天

gre.set(Calendar.DAY_OF_MONTH, 1);

//获得第一天是周几

int weekDay = gre.get(Calendar.DAY_OF_WEEK);

System.out.println("gre="+gre);

System.out.println("today="+today+"\n"+"month="+month+"\n"+"week="+weekDay);

//获得这周第一天星期几

int firstdayofWeek = gre.getFirstDayOfWeek();

System.out.println("firstdayofWeek="+firstdayofWeek);

//获取需要打印空格的数量

int indent= 0;

while(firstdayofWeek != weekDay)

{

indent++;

gre.add(Calendar.DAY_OF_MONTH, -1);

weekDay = gre.get(Calendar.DAY_OF_WEEK);

}

//获得星期

String[] weeksStrs = new DateFormatSymbols().getShortWeekdays();

//打印星期

do

{

String week = weeksStrs[weekDay];

System.out.print(week);

gre.add(Calendar.DAY_OF_MONTH, 1);

weekDay = gre.get(Calendar.DAY_OF_WEEK);

}

while(weekDay != firstdayofWeek);


//换行

System.out.println("");

for (int i = 0;i

{

System.out.print(“”);

}

//设置这个月第一天

gre.set(Calendar.DAY_OF_MONTH, 1);


do

{

int day = gre.get(Calendar.DAY_OF_MONTH);

System.out.printf("%3d", day);

if(day == today)

{

System.out.print("*");

}

gre.add(Calendar.DAY_OF_MONTH, 1);

weekDay = gre.get(Calendar.DAY_OF_WEEK);

if(weekDay == firstdayofWeek)

{

System.out.println("");

}

}

while(gre.get(Calendar.MONTH) == month);

if(weekDay != firstdayofWeek)

{

System.out.println("");

}


结果

星期日星期一星期二星期三星期四星期五星期六

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* 30 31

你可能感兴趣的:(Core in JAVA01 GregorianCalendar 类的使用)