import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class CalendarTest3 {
<span style="white-space:pre"> </span>public static void main(String[] args) {
<span style="white-space:pre"> </span>System.out.printf("今天的日期是: %tF %<tA ,今日所在月份的日历如下:\n\n" , new Date() );
<span style="white-space:pre"> </span>System.out.println("日\t一\t二\t三\t四\t五\t六");
<span style="white-space:pre"> </span>Calendar dt = new GregorianCalendar( );
<span style="white-space:pre"> </span>int month = dt.get( Calendar.MONTH ); //记录当月月份
<span style="white-space:pre"> </span>int today = dt.get( Calendar.DAY_OF_MONTH );//记录当天
<span style="white-space:pre"> </span>//将当前日历定位到当月的1号上。
<span style="white-space:pre"> </span>dt.set( Calendar.DAY_OF_MONTH, 1 );
<span style="white-space:pre"> </span>//获取1号对应的星期是什么
<span style="white-space:pre"> </span>int weekday = dt.get( Calendar.DAY_OF_WEEK );
<span style="white-space:pre"> </span>//打印星期日至1号对应星期间的空格。
<span style="white-space:pre"> </span>for( int w = Calendar.SUNDAY; w < weekday; w++ ){
<span style="white-space:pre"> </span>System.out.print(" ");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>//读取当月的每一天
<span style="white-space:pre"> </span>int m1 = dt.get( Calendar.MONTH );
<span style="white-space:pre"> </span>while( m1 == month ){ //判断从日历中读取的月份是否等于当月
<span style="white-space:pre"> </span>int day = dt.get( Calendar.DAY_OF_MONTH ); //读取日子
<span style="white-space:pre"> </span>if( day == today ){
<span style="white-space:pre"> </span>System.out.printf( "%02d★\t" , day ); //打印当天
<span style="white-space:pre"> </span>}else{
<span style="white-space:pre"> </span>System.out.printf( "%02d\t" , day ); //打印当天
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>weekday = dt.get( Calendar.DAY_OF_WEEK ); //获取日子对应的星期
<span style="white-space:pre"> </span>if( weekday == Calendar.SATURDAY ){
<span style="white-space:pre"> </span>System.out.println(); //换行
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>dt.add( Calendar.DAY_OF_MONTH, 1 ); //进入明天
<span style="white-space:pre"> </span>m1 = dt.get( Calendar.MONTH ); //读取月份
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
}
java输出当月日历
最新推荐文章于 2021-05-07 20:21:52 发布