2014-11-16 69 views
0

我知道如何創建正常的日曆,這將是這樣的。打印日曆

代碼:

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

public class CalendarDateExample { 

    public static void main(String[] args) { 
     // Create an instance of a GregorianCalendar 
     Calendar calendar = new GregorianCalendar(2014, 1, 06); 

     System.out.println("Year: " + calendar.get(Calendar.YEAR)); 
     System.out.println("Month: " + (calendar.get(Calendar.MONTH) + 1)); 
     System.out.println("Day: " + calendar.get(Calendar.DAY_OF_MONTH)); 

     // Format the output. 
     SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd"); 
     System.out.println(date_format.format(calendar.getTime())); 
    } 
} 

輸出: 年時間:2014年 月:2 日:6 2014年2月6日

但如何將顯示給定月份和年份使其壓延看起來像:

July 2005 
    S M T W Th F S 
       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 

我是新來的java,想知道如何做到這一點上面的方式。任何幫助將是偉大的! 由於事先

+0

一個java'Calendar'不是一個月的表示,但一些 「工具」 使用日期的工作。你將不得不實現完整的邏輯才能使輸出看起來像'cal'是一個 –

+0

你想在控制檯,網頁上,桌面應用中顯示這種日曆嗎?您使用的'Calendar'類只是用於表示和轉換時間,而不是以一種整潔的方式顯示它。根據您正在開發的應用程序,可能有十幾個庫可以處理這些功能。 您的目標是開發一個簡單的控制檯應用程序(通過提供的代碼來判斷)? – toniedzwiedz

+0

@rc是否有可能你可以發佈一個鏈接或類似的東西,這將有助於開始與此? –

回答

1

你可以這樣做:

Calendar calendar = new GregorianCalendar(2014, 1, 06); 
calendar.set(Calendar.DAY_OF_MONTH, 1); //Set the day of month to 1 
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); //get day of week for 1st of month 
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 

//print month name and year 
System.out.println(new SimpleDateFormat("MMMM YYYY").format(calendar.getTime())); 
System.out.println(" S M T W T F S"); 

//print initial spaces 
String initialSpace = ""; 
for (int i = 0; i < dayOfWeek - 1; i++) { 
    initialSpace += " "; 
} 
System.out.print(initialSpace); 

//print the days of the month starting from 1 
for (int i = 0, dayOfMonth = 1; dayOfMonth <= daysInMonth; i++) { 
    for (int j = ((i == 0) ? dayOfWeek - 1 : 0); j < 7 && (dayOfMonth <= daysInMonth); j++) { 
     System.out.printf("%2d ", dayOfMonth); 
     dayOfMonth++; 
    } 
    System.out.println(); 
} 

輸出:

February 2014 
S M T W T F S 
        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