2011. 6. 27. 19:14

자바(Java)에서 Calendar와 Date 클래스로 날짜, 요일, 시간 구하기

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

public class DateTime {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance() ;
        
        int year = calendar.get(calendar.YEAR) ;
        int month = calendar.get(calendar.MONTH) + 1 ;
        int date = calendar.get(calendar.DATE) ;
        int day = calendar.get(calendar.DAY_OF_WEEK) ;

        int hour = calendar.get(calendar.HOUR) ;
        int minute = calendar.get(calendar.MINUTE) ;
        int second = calendar.get(calendar.SECOND) ;
        int ampm = calendar.get(calendar.AM_PM) ;

        String apm, conversionDay = null ;        

        switch (day) {        
            case 1 :
                conversionDay = "일" ;
                break ;

            case 2 :
                conversionDay = "월" ;
                break ;
    
            case 3 :
                conversionDay = "화" ;
                break ;

            case 4 :
                conversionDay = "수" ;
                break ;
        
            case 5 :
                conversionDay = "목" ;            
                break ;

            case 6 :
                conversionDay = "금" ;
                break ;

            case 7 :
                conversionDay = "토" ;        
        }

        if (ampm == calendar.AM) {
            apm = "AM" ;
        }

        else {
            apm = "PM" ;
        }

        System.out.println("현재시각 : "+year+"년 "+month+"월 "+date+"일 "+conversionDay 
                                           +"요일 "+apm+" "+hour+"시 "+minute+"분 "+second+"초") ;
    }
}