Calculation of the calendar for a given month
-
The point is, it doesn't seem right in the first week. It's all crazy. Any month. I've been asking for years and months. I don't understand the problem. Help me.
import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar;
public class JavaApplication1 {
public static void main(String[] args){
Date time = new Date();
System.out.println(time);
GregorianCalendar now = new GregorianCalendar();
int today = now.get(Calendar.DAY_OF_MONTH);
int month = now.get(Calendar.MONTH);
now.set(Calendar.DAY_OF_MONTH, 1);
int weekday = now.get(Calendar.DAY_OF_WEEK);
int FirstDayOfWeek = now.getFirstDayOfWeek();
int in = 0;
while (weekday != FirstDayOfWeek){
in++; //счетчик
now.add(Calendar.DAY_OF_MONTH, -1);
weekday = now.get(Calendar.DAY_OF_WEEK);
}
String [] WeekDayNames = new DateFormatSymbols().getShortWeekdays();
do{
System.out.printf("%4s", WeekDayNames[weekday]);
now.add(Calendar.DAY_OF_MONTH, 1);
weekday = now.get(Calendar.DAY_OF_WEEK);
}while(weekday != FirstDayOfWeek);
System.out.println();
for(int i = 1; i<=in; i++)
System.out.print(" ");//тут выводит пробелы на первой неделе месяцяnow.set(Calendar.DAY_OF_MONTH, 1); do{ int day = now.get(Calendar.DAY_OF_MONTH); System.out.printf("%3d", day); if(day == today) System.out.print("*"); else System.out.print(" "); now.add(Calendar.DAY_OF_MONTH, 1); weekday = now.get(Calendar.DAY_OF_WEEK); if (weekday == FirstDayOfWeek) System.out.println(); } while(now.get(Calendar.MONTH) == month); if(weekday != FirstDayOfWeek) System.out.println();
}
♪
-
In you
in
- the difference between the first day of the week and the beginning of the month. Each day in the calendar takes 3 positions per number (format"%3d"
and one position on the marker of the current day" "
or"*"
)That's why you have to take four breaks in the cycle for one day.