Printing a calendar [closed]

有些话、适合烂在心里 提交于 2021-02-16 15:38:25

问题


I know how to create normal calendar which would be something like this.

code:

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()));
    }
} 

Output : Year: 2014 Month: 2 Day: 6 2014-02-06

But how would display a calender for given month and year making it look like:

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 

I am new to java , would like know how to do it the way above. any help would be great! thanks in advance


回答1:


You could do this:

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();
}

Output:

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 


来源:https://stackoverflow.com/questions/26962388/printing-a-calendar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!