날짜 date 보다는 calendar을 쓰라고 권고한다.
Date WrapperClassTest.java 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 public class DateTest { public static void main (String[] args) { Date now = new Date (); System.out.println( now ); printDate1(now); printDate2(now); Date d1 = new Date (100 , 7 , 4 , 14 , 30 , 30 ); printDate2( d1 ); Date d3 = new Date ( 24L * 60 * 60 * 1000 * 365 * 30 ); printDate2(d3); } private static void printDate1 ( Date date ) { SimpleDateFormat sdf = new SimpleDateFormat ( "YYYY년 MM월 dd일 hh시 mm분 ss초" ); System.out.println(sdf.format(date)); } private static void printDate2 ( Date date) { int year = date.getYear(); int month = date.getMonth(); int day = date.getDay(); int hour = date.getHours(); int minutes = date.getMinutes(); int seconds = date.getSeconds(); System.out.println( (year + 1900 ) + "년 " + (month + 1 )+ "월 " + day + "일 " + hour + "시 " + minutes + "분" + seconds + "초" ); } }
싱글톤 어플리케이션에서 객체 하나만 유지하고 싶을 떄 이 방법을 쓴다.
Singleton.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class Singleton { private static Singleton instance; public static Singleton getInstance () { if (instance == null ) { instance = new Singleton (); } return instance; } private Singleton () { } }
싱글톤 클래스를 활용해보자
SingletonTest.java 1 2 3 4 5 6 7 8 9 10 11 12 public class SingletonTest { public static void main (String[] args) { Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); Singleton s3 = Singleton.getInstance(); System.out.println(s1 == s2); System.out.println(s2 == s3); } }
Calendar Calendar클래스는 추상클래스이다.(객체생성 불가능)
WrapperClassTest.java 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 public class CalendarTest { public static void main (String[] args) { Calendar cal = Calendar.getInstance(); printDate( cal ); } public static void printDate ( Calendar cal ) { String[] days = {"일" ,"월" ,"화" ,"수" ,"목" ,"금" ,"토" }; int year = cal.get( Calendar.YEAR ); int month = cal.get( Calendar.MONTH ); int date = cal.get( Calendar.DATE ); int day = cal.get( Calendar.DAY_OF_WEEK); int hour = cal.get( Calendar.HOUR ); int minute = cal.get( Calendar.MINUTE ); int seconds = cal.get( Calendar.SECOND ); System.out.println( (year) + "년 " + (month + 1 )+ "월 " + date + "일 " + "(" + days[day-1 ] + ")" + hour + "시 " + minute + "분" + seconds + "초" ); } }
WrapperClassTest.java