Java 현재시간, 날짜

Java 2009. 5. 25. 11:45
□ 현재 시간, 날짜 구하기
// 밀리초 (1000 = 1초)
long lTime = System.currentTimeMillis();
System.out.println(lTime.toString());

// 현재 시간
Data dDay = new Date();
System.out.println(dDay);

// 포맷을 지정해서 날짜 구하기
SimpleDateFormat sdf = new SimpleDateFormat("yyy.MM.dd HH:mm:ss", Locale.KOREA);
Date dTime = new Date();
String sTime = sdf.format(dTime);
System.out.println(sTime);



□ Date를 Calendar로
Date d = new Date();
Calendar c = Calendar.getInstance();
c.setTime(d);



□ 날짜를 n만큼 이동시키기
// case 1
Date d = new Date();
long lTime = d.getTime();
lTime = lTime + (24*60*60*1000) * n;

// case 2
// 오늘
Calendar cal = Calendar.getInstance();
// 2달 전
cal.add( cal.MONTH, -2 );
// 2일 전
cal.add( cal.DAY_OF_MONTH, -2 );
// 2년 후
cal.add( Calendar.YEAR, 2 );
// print
System.out.println( cal.get( cal.YEAR ) );
System.out.println( cal.get( cal.MONTH ) + 1 );
System.out.println( Calendar.DAY_OF_MONTH ) );



□ 해당하는 달의 마지막날 구하기
// case 1
GregorianCalendar today = new GregorianCalendar();
int endDay = today.getActualMaximum( ( today.DAY_OF_MONTH ) );
System.out.println( endDay ); 

// case 2
Calendar cal = Calendar.getInstance();
cal.set ( 2008, 0, 1 ); //월은 0부터 시작
int endDay = cal.getActualMaximum ( Calendar.DATE );
System.out.println(endDay);



□ 요일구하기
Calendar cal= Calendar.getInstance ( );
//day_of_week가 1이면 일요일, 2이면 월요일.... 7이면 토요일
int day_of_week = cal.get ( Calendar.DAY_OF_WEEK );



□ 날짜, 시간 유효성 검사
// case 1
try {
   DateFormat df = DateFormat.getDateInstance( DateFormat.SHORT );
   df.setLenient( false );
   Date dt2 = df.parse( dt );                       
} catch(ParseException e) {
} catch(IllegalArgumentException e) {
}

// case 2
String result = "";
dateValue = dateValue.replaceAll("-", "");
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM", java.util.Locale.KOREA);

//일자, 시각해석을 엄밀하게 실시할지 설정함
//true일 경우는 엄밀하지 않는 해석, 디폴트
formatter.setLenient ( false );
Date formatDate = null;
try {
   formatDate = formatter.parse( dateValue );
} catch(java.text.ParseException e) {
   return "ERROR";
}



□ 두 날짜 비교
Date date1 = new Date();
Date date2 = new Date();
long ldate1 = date1.getTime();
long ldate2 = date2.getTime();
long diff;
diff = ldate2 - ldate1;
//결과값이 몇시간, 몇일 차이나는지 확인하기 위해선.
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis( diff );
posted by 느릅나무™

Java split 사용법

Java 2009. 5. 25. 11:30
□ 문자열을 구분자로 자를때

- "1:2:3::::" 문자열을 ":" 기준으로 자른다.
○ limit 가 0 인 경우
   String abc = "1:2:3::::";
   String regex = ":";
   int limit = 0;
   String[] results = abc.split(regex, limit);

   결과 ("1", "2", "3")
   zero length string 은 무시된다.

○ limit 가 양수인 경우
   String abc = "1:2:3::::";
   String regex = ":";
   int limit = 5;
   String[] results = abc.split(regex, limit);

   결과 ("1", "2", "3", "", "::")
   배열의 최대갯수는 limit를 넘지 못한다.

○ limit 가 음수인 경우
   String abc = "1:2:3::::";
   String regex = ":";
   int limit = -1;
   String[] results = abc.split(regex, limit);

   결과 ("1", "2", "3", "", "", "", "")
   zero length string 도 포함한다.



□ 문자열 나누기 ( StringTokenizer, split의 차이 )

   String str = "ibzkenshin,nowon,,abc@kbs.com";

   String[] values = str.split(",", 4);
   out.println(str+"<br>");

   for( int x = 0; x < values.length; x++ ){
        out.println( "문자(열) " + (x+1) + " : " + values[x] +"<br>");
   }

   StringTokenizer tokens = new StringTokenizer( str, "," );
   out.println(str+"<br>");

   for( int x = 1; tokens.hasMoreElements(); x++ ){
       out.println( "문자(열) " + x + " : " + tokens.nextToken() + "<br>");
   } 

   // 결과

   * split는 값의 갯수를 주면 빈값도 처리되나 제한값을 알아야 한다.

      kk,mmm,,abc@hanmail.net
      문자(열) 1 : kk
      문자(열) 2 : mmm
      문자(열) 3 :
      문자(열) 4 : abc@hanmail.net 

   * StringTokenizer는 빈값은 무시하고 처리한다.

      kk,mmm,,abc@hanmail.net
      문자(열) 1 : kk
      문자(열) 2 : mmm
      문자(열) 3 : abc@hanmail.net


posted by 느릅나무™

Java 한글 Encoding

Java 2009. 5. 25. 11:18
□ JDK 1.2에서 지원되는 한글 관련 인코딩

○ 유니코드 문자 외부 인코딩
  "UTF8"                           // UTF-8
  "Unicode"                       // Unicode 2 bytes external encoding with byte order mark
  "UnicodeBig"                  // Unicode 2 bytes external big endian encoding with byte order mark
  "UnicodeLittle"                // Unicode 2 bytes external little endian encoding with byte order mark
  "UnicodeBigUnmarked"    // Unicode 2 bytes external big endian encoding with no byte order mark
  "UnicodeLittleUnmarked"  // Unicode 2 bytes external little endian encoding with no byte order mark

○ 아스키 인코딩
  "Default"
  "ASCII"  /* alias: */ "us-ascii"

○ 한국 문자 인코딩
  "EUC_KR"    // Korean, KS C 5601-1987, EUC Encoding
  /* alias: */ "euc-kr", "euckr", "KSC5601", "ksc_5601",
  /* alias: */ "ksc5601_1987", "ks_c_5601-1987", "ksc5601-1987",
  "Cp949", "Cp949C"  // Korean, PC
  "Cp970"                 // Korean, AIX

  "Johab"  // KS C 5601-1992, Microsoft Unified Hangul Encoding
               // (US-ASCII + KS C 5601-1987 + 11172 Modern Hangul Syllables ?)
  /* alias: */ "ms949", "windows-949", "ksc5601-1992", "ksc5601_1992",

  "ISO2022KR"  // Korean, ISO 2022 KR

  "Cp933"    // Korean Mixed with 1880 UDC, superset of 5029


□ JDK 1.5에서 지원되는 한글 관련 인코딩

○ 유니코드 문자 외부 인코딩
  "UTF8"
  "Unicode"
  "UnicodeBig"
  "UnicodeLittle"
  "UnicodeBigUnmarked"
  "UnicodeLittleUnmarked"

○ 아스키 인코딩
  "Default"

○ 한국 문자 인코딩
  "KSC5601"    // Korean, KS C 5601-1987, EUC Encoding
  /* alias: */ "ksc_5601", "ks_c_5601-1987"
  /* alias: */
  "Cp949", "Cp949C"  // Korean, PC
  "Cp970"   // Korean, AIX

  "ISO2022KR"   // Korean, ISO 2022 KR

  "Cp933"  // Korean Mixed with 1880 UDC, superset of 5029
posted by 느릅나무™