Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Calendar;
import java.util.Date;

public class Main {

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        calendar.set(Calendar.DAY_OF_MONTH, 1);
        // day of week for first date of month
        int weekOfFirstDate = calendar.get(Calendar.WEEK_OF_YEAR);

        int lastDateOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, lastDateOfMonth);
        // day of week for last date of month

        int weekOfLastDate = calendar.get(Calendar.WEEK_OF_YEAR);

        calendar.roll(Calendar.MONTH, false);
        int lastDateOfPrevMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        int weeksToDisplay = weekOfLastDate - weekOfFirstDate + 1;
        int[] days = new int[weeksToDisplay * 7];

        int firstDayPosition = 3;

        // fill previous month
        int x = lastDateOfPrevMonth;
        for (int i = firstDayPosition - 1; i >= 0; i--) {
            days[i] = x--;
        }

        // fill current month
        for (int i = 1; i < lastDateOfMonth + 1; i++) {
            days[firstDayPosition - 1 + i] = i;
        }

        // fill next month
        int j = 1;
        for (int i = lastDateOfMonth + firstDayPosition; i < days.length; i++) {
            days[i] = j++;
        }

        for (int i = 0; i < days.length; i++) {
            if (i % 7 == 0) {
                System.out.println();
            }
            System.out.print(days[i] + "\t");
        }
    }
}