본문 바로가기
자바

자바 특정일의 요일 구하기 [김철수홍길동]

by 세상 모든 것 들은 그 자신을 위해 존재한다. 2021. 2. 4.

자바 특정일의 요일 구하기

사용 예제 ) 코드를 복붙 하여 실행해 보시기 바랍니다.

설명은 주석과 코드 아랫부분에 있습니다.

import java.time.DayOfWeek;
import java.time.LocalDate;

public class TestMain {

	public static void main(String[] args) {
		
		
		//--------------특정일의 요일을 돌려받는 예제입니다. ----------
		//인자로 특정 일을 주면 되겠습니다.
		//특정달의 일수를 알아보기위해서는 마지막 일자는 중요하지 않습니다.
		//넣어주기만 하면 됩니다.
		LocalDate newDate = LocalDate.of(2021, 02,1);
		LocalDate newDate2 = LocalDate.of(2021, 02,2);
        
		
       
        
        //데이터 타입이 DayOfWeek 입니다.
		//문자열로 도 쉽게 변환이 됩니다.
		//원하는 형태로 사용하시면 되겠습니다.
		DayOfWeek week1 = newDate.getDayOfWeek();
        String strWeek2 = newDate2.getDayOfWeek().toString();
        
		//출력해서 결과를 알아 봅니다.
			
		System.out.println("2021, 02,1일 의 요일은 : "+week1);		
		System.out.println("2021, 02,2일 의 요일은 : "+strWeek2);		
		

}
}
//출력결과 :


//2021, 02,1일 의 요일은 : MONDAY
//2021, 02,2일 의 요일은 : TUESDAY




 자바로 달력을 말들때 기본적으로 필요한 부분입니다.

특정일의 요일을 구해서 달력의 시작점을 잡으면 되겠습니다.

 

아래는 실전 예제 입니다.

참고용으로 올립니다.

import java.text.DateFormatSymbols;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.GregorianCalendar;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Calendar extends Application{
    private BorderPane containerPane = new BorderPane();
    private GridPane monthPane = new GridPane();
    private Scene scene;
    private LocalDateTime date = LocalDateTime.now();
    // ---------------------------------------------- \\
    Label lblMonth;
    Label lblYear;
    int currentYear = date.getYear();
    int currentMonthInt = date.getMonthValue();

    YearMonth firstAndLastDay;
    String strFirstWeek;
    String strLastWeek;

    GregorianCalendar leapYearCheck = (GregorianCalendar) GregorianCalendar.getInstance();

    int dateInt = 0;
    Text[] daysArr = new Text[42];

    @Override //<<<<<<<<<<<<<<>>>>>>>>>>>>>>\\
    public void start(Stage primaryStage){

        scene = new Scene(containerPane, 900, 650);
        setupCalendarPane();
        primaryStage.setTitle("Calendar");
        primaryStage.setMinWidth(900);
        primaryStage.setMinHeight(620);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public void setupCalendarPane(){
        monthPane.setStyle("-fx-background-color: Blue; -fx-vgap: 1; -fx-hgap: 1; -fx-padding: 1");
        monthPane.setPadding(new Insets(10));
        containerPane.setPadding(new Insets(10));

        for(int i = 0; i < 42; i++){
            daysArr[i] = new Text("");
        }
        //int currentYear = date.getYear();
        //int currentMonthInt = date.getMonthValue();
        firstAndLastDay = YearMonth.of(currentYear, currentMonthInt); // YearMonth
        
        //현재의 년도와 달을 받아온다.
        System.out.println("firstAndLastDay :"+firstAndLastDay);
        
        //그달의 1일을 요일로 받아온다.
        strFirstWeek = firstAndLastDay.atDay(1).getDayOfWeek().name(); // String
        System.out.println("strFirstWeek :"+strFirstWeek);

        //그달의 마지막날을 요일로 받아온다.
        strLastWeek = firstAndLastDay.atEndOfMonth().getDayOfWeek().name(); // String
        System.out.println("strLastWeek :"+strLastWeek);

        //월표시 레이블
        lblMonth = new Label(date.getMonth() + "");
        lblMonth.setFont(Font.font(19));
        
        //년표시 레이블
        lblYear = new Label(currentYear + "");
        lblYear.setFont(Font.font(29));
        
        
        //맨윗줄 레이블을 넣을 hbox를 5개 만든다.
        	//왼쪽정렬후 년과 월을 넣는다.
        HBox topLeft = new HBox(5); topLeft.setAlignment(Pos.BASELINE_LEFT);
        topLeft.getChildren().addAll(lblMonth, lblYear);

        //월단위 이동할 버튼을 만든다.
        Button btnLeftNav = new Button("<");
        Button btnToday = new Button("Today");
        Button btnRightNav = new Button(">");
        
        //hbox10개를만들어 오른쪽정렬한다. 내용은 위의 버튼이 3개 들어간다.
        HBox topRight = new HBox(10); topLeft.setAlignment(Pos.BASELINE_RIGHT);
        topRight.getChildren().addAll(btnLeftNav, btnToday, btnRightNav);
        
//hbox를 사용해서 윗줄을 정리합니다.
        HBox topBox = new HBox(530);
        topBox.setPadding(new Insets(10));
        topBox.getChildren().addAll(topLeft, topRight);

        //topBox.prefWidth(980);
        topLeft.prefWidthProperty().bind(topBox.widthProperty().divide(2));
        topRight.prefWidthProperty().bind(topBox.widthProperty().divide(2));

        //보드페인안에 윗줄에는 윗줄의 hbox를 넣고
        //가운데에는 그리드페인을 넣는다.
        containerPane.setTop(topBox); // Top box
        containerPane.setCenter(monthPane); // Center box
        
        
        fillUpCalendar();

        // Adding actions
        btnLeftNav.setOnAction(e ->{
            containerPane.getChildren().remove(monthPane);
            if(currentMonthInt == 1){
                currentYear--;
                currentMonthInt = 12;
            }
            else
                currentMonthInt--;

            String monthName = new DateFormatSymbols().getMonths()[currentMonthInt - 1];
            lblMonth.setText(monthName.toUpperCase());
            lblYear.setText(currentYear + "");

            fillUpCalendar();
            containerPane.setCenter(monthPane);
        });

        btnToday.setOnAction(e ->{
            containerPane.getChildren().remove(monthPane);
            LocalDateTime dt = LocalDateTime.now();
            currentMonthInt = dt.getMonthValue();
            currentYear = dt.getYear();
            lblMonth.setText(dt.getMonth() + "");
            lblYear.setText(dt.getYear() + "");
            fillUpCalendar();
            containerPane.setCenter(monthPane);
        });

        btnRightNav.setOnAction(e ->{
            containerPane.getChildren().remove(monthPane);
            if(currentMonthInt == 12){
                currentYear++;
                currentMonthInt = 1;
            }
            else
                currentMonthInt++;

            String monthName = new DateFormatSymbols().getMonths()[currentMonthInt - 1];
            lblMonth.setText(monthName.toUpperCase());
            lblYear.setText(currentYear + "");
            fillUpCalendar();
            containerPane.setCenter(monthPane);
        });
    }

    public void fillUpCalendar(){

        firstAndLastDay = YearMonth.of(currentYear, currentMonthInt); // YearMonth
        strFirstWeek = firstAndLastDay.atDay(1).getDayOfWeek().name(); // String
        strLastWeek = firstAndLastDay.atEndOfMonth().getDayOfWeek().name(); // String
        System.out.println("strFirstWeek"+strFirstWeek);
        System.out.println("strLastWeek"+strLastWeek);
        Text[] days = {
            new Text("Sunday"), new Text("Monday"), new Text("Tuesday"),
            new Text("Wednesday"), new Text("Thursday"), new Text("Friday"),
            new Text("Saturday")
        };
       
        // Filling the name of the days, Sunday, Monday ....
        for(int i = 0, j = 0; j < 7; j++){
            StackPane stackPane = new StackPane();
            Rectangle rec = new Rectangle(127, 40);

            //rec.widthProperty().bind(monthPane.widthProperty().divide(7));
            //rec.heightProperty().bind(monthPane.heightProperty().divide(16));
            stackPane.getChildren().addAll(rec, days[j]);
            rec.setFill(Color.WHITE);
            monthPane.add(stackPane, j, i);
        }

        int dateOf = 0;
        int nCol = 1;
        int nRow = 0;
        int nPrevious = 0;
        int nextMonthDate = 0;
        int nextCol = 0;
        int nextRow = 0;
        
        LocalDate newDate = LocalDate.of(currentYear, currentMonthInt, 1);
        int lengthOfMon = newDate.lengthOfMonth();
        System.out.println("lengthOfMon :lengthOfMon"+lengthOfMon);
        
        // Filling the dates 1, 2, 3 .....
        for(nCol = 1; nCol < 7; nCol++){
            if(strFirstWeek.equals("MONDAY") && nCol == 1){
                nRow = 1; nPrevious = nRow;
            }
            else if(strFirstWeek.equals("TUESDAY") && nCol == 1){
                nRow = 2; nPrevious = nRow;
            }
            else if(strFirstWeek.equals("WEDNESDAY") && nCol == 1){
                nRow = 3; nPrevious = nRow;
            }
            else if(strFirstWeek.equals("THURSDAY") && nCol == 1){
                nRow = 4; nPrevious = nRow;
            }
            else if(strFirstWeek.equals("FRIDAY") && nCol == 1){
                nRow = 5; nPrevious = nRow;
            }
            else if(strFirstWeek.equals("SATURDAY") && nCol == 1){
                nPrevious = nRow = 6;
            }
            else nRow = 0;
            // Filling the dates
            for(nRow = nRow; nRow < 7; nRow++){
                if(lengthOfMon == dateOf){
                    nextMonthDate = 42 - dateOf - nPrevious; break;
                }
                dateOf++;
                StackPane stackPane = new StackPane();
                Rectangle rec = new Rectangle(127, 93); // whole month
                //rec.widthProperty().bind(monthPane.widthProperty().divide(7));
                //rec.heightProperty().bind(monthPane.heightProperty().divide(6.5));
                Text dayText = new Text(dateOf + "");
                LocalDateTime date1 = LocalDateTime.now();
                int day = date1.getDayOfMonth();
                int mon = date1.getMonthValue();
                int yr = date1.getYear();
                if(dateOf == day && mon == currentMonthInt && yr == currentYear){
                    Circle cir = new Circle(20);
                    cir.setFill(Color.RED);
                    dayText.setFill(Color.WHITE);
                    rec.setFill(Color.WHITE);
                    stackPane.getChildren().addAll(rec, cir, dayText);
                    monthPane.add(stackPane, row, nCol);
                    nextRow = nRow; nextCol = nCol;
                }
                else{
                    stackPane.getChildren().addAll(rec, dayText);
                    rec.setFill(Color.WHITE);
                    monthPane.add(stackPane, nRow, nCol);
                    nextRow = nRow; nextCol = nCol;
                }
            }
        }

         //Filling dates from nPrevious month
        int len = nPrevious; // 4
        LocalDate ldate = LocalDate.of(currentYear, currentMonthInt, 1);
        if(currentMonthInt == 1){
            ldate = LocalDate.of(currentYear, 12, 1);
        }
        else
            ldate = LocalDate.of(currentYear, currentMonthInt-1, 1);

        int totalD = ldate.lengthOfMonth();
        totalD = totalD - nPrevious;

        for(int j = 0; j < len; j++){
            StackPane stackPane = new StackPane();
            Rectangle rec = new Rectangle(127, 93);
            //rec.widthProperty().bind(monthPane.widthProperty().divide(7));
            //rec.heightProperty().bind(monthPane.heightProperty().divide(6.5));
            rec.setFill(Color.WHITE);
            totalD++;
            Text dayText = new Text(totalD + "");
            dayText.setFill(Color.GRAY);
            stackPane.getChildren().addAll(rec, dayText);
            monthPane.add(stackPane, j, 1);
        }

        // Filling the dates from next month 1, 2, ....
        int temp = 0; int forNextMonth = 0;

        for(int i = nextCol; i < 7; i++){
            if(i < 6) temp = nextRow+1;
            else if(nextMonthDate <= 7) temp = 7 - nextMonthDate;
            else temp = 0;

            for(int j = temp; j < 7; j++){
                forNextMonth++;
                StackPane stackPane = new StackPane();
                Rectangle rec = new Rectangle(127, 93);
                //rec.widthProperty().bind(monthPane.widthProperty().divide(7));
                //rec.heightProperty().bind(monthPane.heightProperty().divide(6.5));
                rec.setFill(Color.WHITE);
                Text dayText = new Text(forNextMonth + "");
                dayText.setFill(Color.GRAY);
                stackPane.getChildren().addAll(rec, dayText);
                monthPane.add(stackPane, j, i);
            }
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
728x90
반응형

댓글