본문 바로가기
Java/Java 알고리즘

[Java] 달력 만들기 / 시간 표시

by ProSeraphina 2020. 7. 2.

1. 알고리즘

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class 달력만들기{
 
    public static void main(String[] args){
        int year=0, month=0;
        Scanner scan=new Scanner(System.in);
        System.out.println("연도 입력:");
        year=scan.nextInt();
        System.out.println("월 입력:");
        month=scan.nextInt();
 
        //출력
        String[] strWeek= {"일","월","화","수","목","금","토"};
        System.out.println(year+"년 "+month+"월");
        for(String week:strWeek) {
            System.out.print(week+"\t");
        }
        
        //요일 구하기
        /* 전년도 총 날수(1년~2019.12.31)
         * 전 달까지의 합(2020.1.1~6.30)
         * +1(1일부터 출력)
         */
        int total=(year-1)*365
                +(year-1)/4
                -(year-1)/100
                +(year-1)/400;
        
        //전 달
        int[] lastDay= {31,28,31,30,31,30,31,31,30,31,30,31};
        if((year%4==0&&year%100!=0)||(year%400==0)){
            lastDay[1]=29;
        }else {
            lastDay[1]=28;
        }
        
        for(int i=0;i<month-1;i++) {
            total+=lastDay[i];
        }
        
        //1일자의 요일
        total++;
        int week=total%7;
        
        //달력 출력
        for(int i=0;i<month-1;i++) {
            total+=lastDay[i];
        }
        
        //입력된 Day
          System.out.println();
          for(int i=1;i<=lastDay[month-1];i++){
             if(i==1){
               for(int j=0;j<week;j++){
                System.out.print("\t");
               }
             }
             System.out.printf("%2d\t",i);
             week++;
             if(week>6) {
                 week=0;
                 System.out.println();
             }
          }
    }
}
cs

 

2. 라이브러리 사용

(추가 예정)

 

3. 시간 표시방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.sist.lib;
import java.util.*;
import java.text.*;
 
public class MainClass{
    public static void main(String[] args){
        Date date=new Date();
        System.out.println(date.toString());
        //Tue Jul 28 19:00:20 KST 2020 => 변환(책 p.544)
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //시: h(1~12시) H(0~23시)
        System.out.println(sdf.format(date));
        //2020-07-28 07:00:20
    }
}
cs

 

댓글