2011년 5월 26일 목요일

Java - java.util.Calendar

Calendar c = Calendar.getInstance(); 


// how to get current date
int year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH);
//JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER

int day = c.get(Calendar.DATE); 

int week = c.get(Calendar.DAY_OF_WEEK); 
//SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY. 

int hour = c.get(Calendar.HOUR); 

int minute = c.get(Calendar.MINUTE); 

int ampm = c.get(Calendar.AM_PM); 
//AM, PM
....
....
....



//how to calculate days between from date and to date

Calendar c2 = Calendar.getInstance();

c2.set(Calendar.YEAR, 1980);
c2.set(Calendar.MONTH, 9);
c2.set(Calendar.DATE, 17); // my BirthDay!!!!

//void set(int field, int value) 
//can use other "set" method (e.g. set(int year, int month, int day), ...)

long gap = c.getTimeInMillis() - c2.getTimeInMillis();
// "getTimeInMillis" returns milliseconds


System.out.println(String.valueOf((int)(gap / 86400000)));
// 1day = 86400000 milliseconds


can use when calculate D-Day, Biorhythm...