java列印日曆

來源:互聯網
上載者:User

原始碼:

import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;public class MyDate {public static void main(String[] args) {MyDate date = new MyDate();date.myCalendar();}//實現日曆的方法public void myCalendar() {GregorianCalendar now = new GregorianCalendar();// 獲得一個Date對象Date date = new Date();// 列印目前時間System.out.println(date.toString());// 設定目前時間now.setTime(date);// 從日期中取得當前的日int toDay = now.get(Calendar.DAY_OF_MONTH);// 從日期中取得當前的月int month = now.get(Calendar.MONTH);// 設定now的日期為1now.set(Calendar.DAY_OF_MONTH, 1);// 得到now是一周的第幾天int week = now.get(Calendar.DAY_OF_WEEK);// 列印日曆頭部標示System.out.println("日\t一\t二\t三\t四\t五\t六");// 列印當前日期前面的空格for (int i = Calendar.SUNDAY; i < week; i++) {System.out.print("\t");}// 列印日曆主體while (now.get(Calendar.MONTH) == month) {int day = now.get(Calendar.DAY_OF_MONTH);// 對輸出的日曆進行對齊,小於10的加上一個空格if (day < 10) {// 如果是當前日期,加上標示if (day == toDay) {System.out.print("▲" + day + "▲\t");} else {System.out.print(" " + day + "\t");}} else {// 如果是當前日期,加上標示if (day == toDay) {System.out.print("▲" + day + "▲\t");} else {System.out.print("" + day + "\t");}}//如果是周六,進行換行if (week == Calendar.SATURDAY) {System.out.println();}//每次輸出日期後,將日期增加一天now.add(Calendar.DAY_OF_MONTH, 1);//重新獲得一周的第幾天week = now.get(Calendar.DAY_OF_WEEK);}}}

輸出結果:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.