자바 컴파일과 실행에 사용되어지는 javac, java 명령어의 옵션 정리

javac - 자바컴파일러로써, 자바코드를 작성한 소스파일(.java)을 자바 가상머신이 인식할수 있는 바이트 코드(.class)
타입으로 변환시켜주는 명령어 입니다.

사용법: javac <options> <souce files>
예를들어, Hello.java, Greeting.java 두개의 파일이 존재한다면,
javac Hello.java Greeting.java
javac *.java (*을 사용해서, 모든 확장자가 .java인 파일을 컴파일할수 있다.)

1) 옵션:

a) -classpath:

 -classpath(cp) path(파일 절대 경로):
 컴파일러가 컴파일 하기 위해서 필요로 하는 참조할 클래스 파일들을 찾기 위해서 컴파일시 파일 경로를 지정해주는
옵션. 예를 들어,  Hello.java파일이 C:\Java 디렉터리에 존재하고, 필요한 클래스 파일들이 C:\Java\Engclasses에 위치한다면,
javac -classpath C:\Java\Engclasses C:\Java\Hello.java 로 해주면 된다. 만약 참조할 클래스 파일들이 C:\Java\Engclasses외의
다른 디렉터리에도 존재한다면, C:\Java\Korclasses 일경우,
javac -classpath C:\Java\Engclasses;C;\Java\Korclasses C:\Java\Hello.java
그리고, 현재 디렉터리역시 포함하고 싶다면,
javac -classpath .;C:\Java\Engclasses;C;\Java\Korclasses C:\Java\Hello.java
기본적으로, dos에서는 .는 현재 디렉터리를 의미하고, ..는 현재 디렉터리의 상위디렉터리를 의미한다.
또한 classpath 대신 단축어인 cp를 사용해도 된다.
javac -cp C:\Java\Engclasses C:\Java\Hello.java 

b) -d:
 -d directory
 클래스 파일을 생성할 루트 디렉터리를 지정합니다.
기본적으로 컴파일러는 -d옵션을 주지 않으면, 소스파일이 위치한 디렉터리에 클래스 파일을 생성시킵니다.
예를 들어,  Hello.java파일이 C:\Java 디렉터리에 존재하고 클래스 파일의 루트디렉터리를 C:\Java\Classfiles라고 하면,
javac -d C:\Java\Classfiles C:\Java\Hello.java 입니다.

만약 -d 옵션을 사용하려고 하는데, 루트디렉터리(위예에서는 C:\Java\Classfiles) 가 존재 하지 않는다면,
"The system cannot find the path specified"라는 에러 메시지를 보게 됩니다.
현재 작업 디렉터리가 C:\Java\Classfiles 에 위치하면,
javac -d .\Classfiles Hello.java 와 같이 상대 디렉터리로 표현할수 있습니다.

java class내에서 package를 선언한 경우 package별 폴더를 생성하고 해당 폴더에(package) compile한다.

c) -encoding:
-encoding encoding name
소스 파일에 사용된 문자열 인코딩을 설정합니다.
만약 위옵션이 설정되어 있지 않으면, 플래폼의 기본적인 컨버터가 사용되어 집니다.

d) -g:
모든 디버깅 정보를 생성시킵니다.
만약 위옵션이 설정되어 있지 않으면, 기본적으로, 라인넘버만 생성시킵니다.
-g:none: 디버깅 정보를 전혀 생성 시키지 않습니다.
-g:{lines, vars, source}:
위처럼 명시적으로, 몇몇 디버깅 정보를 생성시킬수 있습니다.
lines은 라인정보, vars는 지역변수, sounce는 소스 파일 정보를 나타냅니다.

e) -nowarn:

경고 메시지 (warning message)를 생성시키지 않습니다.

f) -verbose:

컴파일러와 링커가 현재 어느 소스파일이 컴파일되고 있고, 어느 파일이 링크되고 있는지
그정보를 출력한다.

h) -deprecation:

소스 코드내에서, 사용되어진 deprecated API의 위치 를 출력 합니다.

ex)
C:\Java> javac World.java
Note: World.java uses a deprecated API. Recompile with "-deprecation" for details
.
1 warning
C:\Java> javac -deprecation World.java
World.java:52: Note: The method java.awt.Dimension size() in class java.awt.Compon
ent has been deprecated.
Dimension d = size();

Note: World.java uses a deprecated API. Please consult the documentation for a be
tter alternative.

i) -sourcepath:

-sourcepath 소스패스

소스파일의 위치를 지정합니다.

j) -target:

-target 자바버젼

지정된 자바버젼의 VM에서 작동 되어지도록 클래스파일을 생성 시킵니다.

1.1
jvm 1.1 버젼에서 호환되어질수 있는 클래스 파일생성
1.2
jvm 1.2 버젼에서 호환되어질수 있는 클래스 파일생성
1.3
jvm 1.3 버젼에서 호환되어질수 있는 클래스 파일 생성

ex)

javac -target 1.2 Helloworld.java

k) -bootclasspath 패스:

특정한 bootstrap또는 확장 클래스를 지정할수 있다.
기본적으로, 자바컴파일러는 javac(컴파일러명령)이 설치된 플래폼의 bootstrap과 확장클래스들을 통해서, 컴파일작업을 수행하지만,
bootclasspath 옵션을 사용하면, cross-compiling이라고 해서, 다른 자바플래폼의 bootstrap과 확장클래스들을 통해서, 컴파일 할수 있는 기능을 지원한다.
예를들어,
javac -target 1.1 -bootclasspath jdk1.1.7/lib/classes.zip -extdirs "" OldCode.java
컴파일러에게 현재 자신의 bootstrap을 사용하지 말고, jdk1.1.7/lib/classes.zip bootstrap클래스들을 사용해서 컴파일 하라고
명령하는것이다.
참고로, 모바일자바에서, 모바일폰에 설정된, jvm에 맞도록, 소스코드를 컴파일하기 위해서, 주로 사용되어지는 옵션이다.

l) -extdirs 디렉터리:
특정한, 확장 디렉토리를 지정한다.cross-compiling시 주로, 사용되어지는 옵션이면, 각디렉터리들은 콜론(:)에 의해서, 분리되어진다.
컴파일시, 기술한 디렉터리의 클래스 파일을 참조한다.

======================================================

출처 : http://blog.naver.com/darkhan1?Redirect=Log&logNo=10009423507

java 컴파일시 알아 두면 유용하게 쓰일거 같다..

#################################################
Usage: javac <options> <source files>
where possible options include:
  -g                                  Generate all debugging info
  -g:none                          Generate no debugging info
  -g:{lines,vars,source}     Generate only some debugging info
  -nowarn                         Generate no warnings
  -verbose                        Output messages about what the compiler is doing
  -deprecation                   Output source locations where deprecated APIs are used
  -classpath <path>           Specify where to find user class files and annotation processors
  -cp <path>                     Specify where to find user class files and annotation processors
  -sourcepath <path>         Specify where to find input source files
  -bootclasspath <path>      Override location of bootstrap class files
  -extdirs <dirs>                Override location of installed extensions
  -endorseddirs <dirs>       Override location of endorsed standards path
  -proc:{none,only}            Control whether annotation processing and/or compilation is done.
  -processor <class1>[,<class2>,<class3>...]

                                       Names of the annotation processors to run; bypasses default discovery process
  -processorpath <path>      Specify where to find annotation processors
  -d <directory>                 Specify where to place generated class files
  -s <directory>                 Specify where to place generated source files
  -implicit:{none,class}      Specify whether or not to generate class files for implicitly referenced files
  -encoding <encoding>       Specify character encoding used by source files
  -source <release>          Provide source compatibility with specified release
  -target <release>            Generate class files for specific VM version
  -version                         Version information
  -help                             Print a synopsis of standard options
  -Akey[=value]                Options to pass to annotation processors
  -X                                 Print a synopsis of nonstandard options
  -J<flag>                         Pass <flag> directly to the runtime system
 
 
 
 
Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)

where options include:
    -client   to select the "client" VM
    -server   to select the "server" VM
    -hotspot   is a synonym for the "client" VM  [deprecated]
                  The default VM is client.
                 
    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
                  A ; separated list of directories, JAR archives, and ZIP archives to search for class files.
    -D<name>=<value>
                  set a system property
    -verbose[:class|gc|jni]
                  enable verbose output
    -version      print product version and exit
    -version:<value>
                  require the specified version to run
    -showversion  print product version and continue
    -jre-restrict-search | -jre-no-restrict-search
                  include/exclude user private JREs in the version search
    -? -help      print this help message
    -X            print help on non-standard options
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=<options>]
                  load native agent library <libname>, e.g. -agentlib:hprof
                    see also, -agentlib:jdwp=help and -agentlib:hprof=help
    -agentpath:<pathname>[=<options>]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=<options>]
                  load Java programming language agent, see java.lang.instrument
    -splash:<imagepath>
                  show splash screen with specified image
 

M) package 선언된 Java class 실행시키기

- package위치는 CLASSPATH 하위 폴더부터로 인식한다. 따라서 Package폴더의 Root가 ClassPath에 지정되든지

.(현위치)를 ClassPath에 등록 후 현 위치 아래서부터 package의 위치를 지정한다.

java package.class명 (현위치 아래에 package폴더가 존재)

java com.test.SampleMain

import  java.text.*;


public class Test 
{
 public Test(double str, int b)
 {
  String c = "###,###";
  if( b != 0)
  {
   c = c+".";

   for(int i=0;i<b;i++)
   {
    c = c+"#";
   }
  }
//  DecimalFormat fd = new DecimalFormat("###,###.####");
 
  DecimalFormat fd = new DecimalFormat(c);
  String fdVal = fd.format(str);

  System.out.println(fdVal);
 }
 public static void main(String[] args)  throws ParseException
 {
  Test t = new Test(2222222222998.61295, 0);
 }
}

//// b만큼 의 소수점 자리로 반올림된다

[ 날짜 연산법 ]


가. 이해 및 유틸

- 시스템 시간에 대한 이해
- 날짜 계산 종합 유틸리티

나. 응용팁

시스템의 밀리초 구하기.(국제표준시각(UTC, GMT) 1970/1/1/0/0/0 으로부터 경과한 시각)
------------------------------------------------------------------
// 밀리초 단위(*1000은 1초), 음수이면 이전 시각
long time = System.currentTimeMillis ( );
System.out.println ( time.toString ( ) );
------------------------------------------------------------------

현재 시각을 가져오기.
------------------------------------------------------------------
Date today = new Date ();
System.out.println ( today );

결과 : Sat Jul 12 16:03:00 GMT+01:00 2000
------------------------------------------------------------------

경과시간(초) 구하기
------------------------------------------------------------------
long time1 = System.currentTimeMillis ();
long time2 = System.currentTimeMillis ();
system.out.println ( ( time2 - time1 ) / 1000.0 );
------------------------------------------------------------------

Date를 Calendar로 맵핑시키기
------------------------------------------------------------------
Date d = new Date ( );
Calendar c = Calendar.getInstance ( );
c.setTime ( d );
------------------------------------------------------------------

날짜(년/월/일/시/분/초) 구하기
------------------------------------------------------------------
import java.util.*;
import java.text.*;

SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy.MM.dd HH:mm:ss", Locale.KOREA );
Date currentTime = new Date ( );
String dTime = formatter.format ( currentTime );
System.out.println ( dTime );
------------------------------------------------------------------

날짜(년/월/일/시/분/초) 구하기2
------------------------------------------------------------------
GregorianCalendar today = new GregorianCalendar ( );

int year = today.get ( today.YEAR );
int month = today.get ( today.MONTH ) + 1;
int yoil = today.get ( today.DAY_OF_MONTH );

GregorianCalendar gc = new GregorianCalendar ( );

System.out.println ( gc.get ( Calendar.YEAR ) );
System.out.println ( String.valueOf ( gc.get ( Calendar.MONTH ) + 1 ) );
System.out.println ( gc.get ( Calendar.DATE ) );
System.out.println ( gc.get ( DAY_OF_MONTH ) );
------------------------------------------------------------------

날짜(년/월/일/시/분/초) 구하기3
------------------------------------------------------------------
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.KOREA);
Calendar cal = Calendar.getInstance(Locale.KOREA);
nal = df.format(cal.getTime());
------------------------------------------------------------------

- 표준시간대를 지정하고 날짜를 가져오기.
------------------------------------------------------------------
TimeZone jst = TimeZone.getTimeZone ("JST");
Calendar cal = Calendar.getInstance ( jst ); // 주어진 시간대에 맞게 현재 시각으로 초기화된 GregorianCalender 객체를 반환.// 또는 Calendar now = Calendar.getInstance(Locale.KOREA);
System.out.println ( cal.get ( Calendar.YEAR ) + "년 " + ( cal.get ( Calendar.MONTH ) + 1 ) + "월 " + cal.get ( Calendar.DATE ) + "일 " + cal.get ( Calendar.HOUR_OF_DAY ) + "시 " +cal.get ( Calendar.MINUTE ) + "분 " + cal.get ( Calendar.SECOND ) + "초 " );

결과 : 2000년 8월 5일 16시 16분 47초
------------------------------------------------------------------

영어로된 날짜를 숫자로 바꾸기
------------------------------------------------------------------
Date myDate = new Date ( "Sun,5 Dec 1999 00:07:21" );
System.out.println ( myDate.getYear ( ) + "-" + myDate.getMonth ( ) + "-" + myDate.getDay ( ) );
------------------------------------------------------------------

"Sun, 5 Dec 1999 00:07:21"를 "1999-12-05"로 바꾸기
------------------------------------------------------------------
SimpleDateFormat formatter_one = new SimpleDateFormat ( "EEE, dd MMM yyyy hh:mm:ss",Locale.ENGLISH );
SimpleDateFormat formatter_two = new SimpleDateFormat ( "yyyy-MM-dd" );

String inString = "Sun, 5 Dec 1999 00:07:21";

ParsePosition pos = new ParsePosition ( 0 );
Date frmTime = formatter_one.parse ( inString, pos );
String outString = formatter_two.format ( frmTime );

System.out.println ( outString );
------------------------------------------------------------------

숫자 12자리를, 다시 날짜로 변환하기
------------------------------------------------------------------
Date conFromDate = new Date();
long ttl = conFromDate.parse ( "Dec 25, 1997 10:10:10" );
System.out.println ( ttl ); //예 938291839221

Date today = new Date ( ttl );
DateFormat format = DateFormat.getDateInstance ( DateFormat.FULL,Locale.US );
String formatted = format.format ( today );
System.out.println ( formatted );
------------------------------------------------------------------

특정일로부터 n일 만큼 이동한 날짜 구하기
------------------------------------------------------------------
특정일의 시간을 long형으로 읽어온다음..
날짜*24*60*60*1000 을 계산하여.
long형에 더해줍니다.
그리고 나서 Date클래스와 Calender클래스를 이용해서 날짜와 시간을 구하면 됩니다
------------------------------------------------------------------

특정일에서 일정 기간후의 날짜 구하기2
------------------------------------------------------------------
//iDay 에 입력하신 만큼 빼거나 더한 날짜를 반환 합니다.
import java.util.*;

public String getDate ( int iDay )
{
Calendar temp=Calendar.getInstance ( );
StringBuffer sbDate=new StringBuffer ( );

temp.add ( Calendar.DAY_OF_MONTH, iDay );

int nYear = temp.get ( Calendar.YEAR );
int nMonth = temp.get ( Calendar.MONTH ) + 1;
int nDay = temp.get ( Calendar.DAY_OF_MONTH );

sbDate.append ( nYear );
if ( nMonth < 10 )
sbDate.append ( "0" );
sbDate.append ( nMonth );
if ( nDay < 10 )
sbDate.append ( "0" );
sbDate.append ( nDay );

return sbDate.toString ( );
}
------------------------------------------------------------------

현재날짜에서 2달전의 날짜를 구하기
------------------------------------------------------------------
Calendar cal = Calendar.getInstance ( );//오늘 날짜를 기준으루..
cal.add ( cal.MONTH, -2 ); //2개월 전....
System.out.println ( cal.get ( cal.YEAR ) );
System.out.println ( cal.get ( cal.MONTH ) + 1 );
System.out.println ( cal.get ( cal.DATE ) );
------------------------------------------------------------------

달에 마지막 날짜 구하기
------------------------------------------------------------------
for ( int month = 1; month <= 12; month++ )
{
GregorianCalendar cld = new GregorianCalendar ( 2001, month - 1, 1 );
System.out.println ( month + "/" + cld.getActualMaximum ( Calendar.DAY_OF_MONTH ) );
}
------------------------------------------------------------------

해당하는 달의 마지막 일 구하기
------------------------------------------------------------------
GregorianCalendar today = new GregorianCalendar ( );
int maxday = today.getActualMaximum ( ( today.DAY_OF_MONTH ) );
System.out.println ( maxday );
------------------------------------------------------------------

특정일을 입력받아 해당 월의 마지막 날짜를 구하는 간단한 예제.(달은 -1 해준다.)...윤달 30일 31일 알아오기.
------------------------------------------------------------------
Calendar cal = Calendar.getInstance ( );
cal.set ( Integer.parseInt ( args[0] ), Integer.parseInt ( args [1] ) - 1, Integer.parseInt ( args [2] ) );
SimpleDateFormat dFormat = new SimpleDateFormat ( "yyyy-MM-dd" );
System.out.println ( "입력 날짜 " + dFormat.format ( cal.getTime ( ) ) );
System.out.println ( "해당 월의 마지막 일자 : " + cal.getActualMaximum ( Calendar.DATE ) );
------------------------------------------------------------------

해당월의 실제 날짜수 구하기 ( 1999년 1월달의 실제 날짜수를 구하기 )
------------------------------------------------------------------
Calendar calendar = Calendar.getInstance ( );
calendar.set ( 1999, 0, 1 );
int maxDays = calendar.getActualMaximum ( Calendar.DAY_OF_MONTH );
------------------------------------------------------------------

어제 날짜 구하기
------------------------------------------------------------------
오늘날짜를 초단위로 구해서 하루분을 빼주고 다시
셋팅해주면 쉽게 구할수 있죠..
setTime((기준일부터 오늘까지의 초를 구함) - 24*60*60)해주면 되겠죠..
------------------------------------------------------------------

어제 날짜 구하기2
------------------------------------------------------------------
import java.util.*;

public static Date getYesterday ( Date today )
{
if ( today == null )
throw new IllegalStateException ( "today is null" );
Date yesterday = new Date ( );
yesterday.setTime ( today.getTime ( ) - ( (long) 1000 * 60 * 60 * 24 ) );

return yesterday;
}
------------------------------------------------------------------

내일 날짜 구하기
------------------------------------------------------------------
Date today = new Date ( );
Date tomorrow = new Date ( today.getTime ( ) + (long) ( 1000 * 60 * 60 * 24 ) );
------------------------------------------------------------------

내일 날짜 구하기2
------------------------------------------------------------------
Calendar today = Calendar.getInstance ( );
today.add ( Calendar.DATE, 1 );
Date tomorrow = today.getTime ( );
------------------------------------------------------------------

오늘날짜에서 5일 이후 날짜를 구하기
------------------------------------------------------------------
Calendar cCal = Calendar.getInstance();
c.add(Calendar.DATE, 5);
------------------------------------------------------------------

날짜에 해당하는 요일 구하기
------------------------------------------------------------------
//DAY_OF_WEEK리턴값이 일요일(1), 월요일(2), 화요일(3) ~~ 토요일(7)을 반환합니다.
//아래 소스는 JSP일부입니다.
import java.util.*;

Calendar cal= Calendar.getInstance ( );
int day_of_week = cal.get ( Calendar.DAY_OF_WEEK );
if ( day_of_week == 1 )
m_week="일요일";
else if ( day_of_week == 2 )
m_week="월요일";
else if ( day_of_week == 3 )
m_week="화요일";
else if ( day_of_week == 4 )
m_week="수요일";
else if ( day_of_week == 5 )
m_week="목요일";
else if ( day_of_week == 6 )
m_week="금요일";
else if ( day_of_week == 7 )
m_week="토요일";

오늘은 : 입니다.
------------------------------------------------------------------

콤보박스로 선택된 날짜(예:20001023)를 통해 요일을 영문으로 가져오기
------------------------------------------------------------------
//gc.get(gc.DAY_OF_WEEK); 하면 일요일=1, 월요일=2, ..., 토요일=7이 나오니까,
//요일을 배열로 만들어서 뽑아내면 되겠죠.
GregorianCalendar gc=new GregorianCalendar ( 2000, 10 - 1 , 23 );
String [] dayOfWeek = { "", "Sun", "Mon", .... , "Sat" };
String yo_il = dayOfWeek ( gc.get ( gc.DAY_OF_WEEK ) );
------------------------------------------------------------------

두 날짜의 차이를 일수로 구하기
------------------------------------------------------------------
각각의 날짜를 Date형으로 만들어서 getTime()하면
long으로 값이 나오거든요(1970년 1월 1일 이후-맞던가?- 1/1000 초 단위로..)
그러면 이값의 차를 구해서요. (1000*60*60*24)로 나누어 보면 되겠죠.
------------------------------------------------------------------

두 날짜의 차이를 일수로 구하기2
------------------------------------------------------------------
import java.io.*;
import java.util.*;

Date today = new Date ( );
Calendar cal = Calendar.getInstance ( );
cal.setTime ( today );// 오늘로 설정.

Calendar cal2 = Calendar.getInstance ( );
cal2.set ( 2000, 3, 12 ); // 기준일로 설정. month의 경우 해당월수-1을 해줍니다.

int count = 0;
while ( !cal2.after ( cal ) )
{
count++;
cal2.add ( Calendar.DATE, 1 ); // 다음날로 바뀜

System.out.println ( cal2.get ( Calendar.YEAR ) + "년 " + ( cal2.get ( Calendar.MONTH ) + 1 ) + "월 " + cal2.get ( Calendar.DATE ) + "일" );
}

System.out.println ( "기준일로부터 " + count + "일이 지났습니다." );
------------------------------------------------------------------

두 날짜의 차이를 일수로 구하기3
------------------------------------------------------------------
import java.io.*;
import java.util.*;

public class DateDiff
{
public static int GetDifferenceOfDate ( int nYear1, int nMonth1, int nDate1, int nYear2, int nMonth2, int nDate2 )
{
Calendar cal = Calendar.getInstance ( );
int nTotalDate1 = 0, nTotalDate2 = 0, nDiffOfYear = 0, nDiffOfDay = 0;

if ( nYear1 > nYear2 )
{
for ( int i = nYear2; i < nYear1; i++ )
{
cal.set ( i, 12, 0 );
nDiffOfYear += cal.get ( Calendar.DAY_OF_YEAR );
}
nTotalDate1 += nDiffOfYear;
}
else if ( nYear1 < nYear2 )
{
for ( int i = nYear1; i < nYear2; i++ )
{
cal.set ( i, 12, 0 );
nDiffOfYear += cal.get ( Calendar.DAY_OF_YEAR );
}
nTotalDate2 += nDiffOfYear;
}

cal.set ( nYear1, nMonth1-1, nDate1 );
nDiffOfDay = cal.get ( Calendar.DAY_OF_YEAR );
nTotalDate1 += nDiffOfDay;

cal.set ( nYear2, nMonth2-1, nDate2 );
nDiffOfDay = cal.get ( Calendar.DAY_OF_YEAR );
nTotalDate2 += nDiffOfDay;

return nTotalDate1-nTotalDate2;
}

public static void main ( String args[] )
{
System.out.println ( "" + GetDifferenceOfDate (2000, 6, 15, 1999, 8, 23 ) );
}
}
------------------------------------------------------------------

파일에서 날짜정보를 가져오기
------------------------------------------------------------------
File f = new File ( directory, file );

Date date = new Date ( f.lastModified ( ) );
Calendar cal = Calendar.getInstance ( );
cal.setTime ( date );

System.out.println("Year : " + cal.get(Calendar.YEAR));
System.out.println("Month : " + (cal.get(Calendar.MONTH) + 1));
System.out.println("Day : " + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("Hours : " + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("Minutes : " + cal.get(Calendar.MINUTE));
System.out.println("Second : " + cal.get(Calendar.SECOND));
------------------------------------------------------------------

날짜형식으로 2000-01-03으로 처음에 인식을 시킨후
7일씩 증가해서 1년정도의 날짜를 출력해 주고 싶은데요.
------------------------------------------------------------------
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-mm-dd" );
Calendar c = Calendar.getInstance ( );

for ( int i = 0; i < 48; i++ )
{
c.clear ( );
c.set ( 2000, 1, 3 - ( i * 7 ) );
java.util.Date d = c.getTime ( );
String thedate = sdf.format ( d );
System.out.println ( thedate );
}
------------------------------------------------------------------

쓰레드에서 날짜 바꾸면 죽는 문제
------------------------------------------------------------------
Main화면에 날짜와시간이Display되는 JPanel이 있습니다.
date로 날짜와 시간을 변경하면 Main화면의 날짜와 시간이 Display되는 Panel에
변경된 날짜가 Display되지 않고 Main화면이 종료되어 버립니다.

문제소스:
public void run ( )
{
while ( true )
{
try{
timer.sleep ( 60000 );
}
catch ( InterruptedException ex ) { }

lblTimeDate.setText ( fGetDateTime ( ) );
repaint ( );
}
}

public String fGetDateTime ( )
{
final int millisPerHour = 60 * 60 * 1000;
String DATE_FORMAT = "yyyy / MM / dd HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat ( DATE_FORMAT );
SimpleTimeZone timeZone = new SimpleTimeZone ( 9 * millisPerHour, "KST" );
sdf.setTimeZone ( timeZone );

long time = System.currentTimeMillis ( );
Date date = new Date ( time );
return sdf.format ( date );
}

해답:
// 날짜와 요일 구한다. timezone 으로 날짜를 다시 셋팅하시면 됨니다.
public String getDate ( )
{
Date now = new Date ( );
SimpleDateFormat sdf4 = new SimpleDateFormat ( "yyyy/MM/dd HH:mm EE" );
sdf4.setTimeZone ( TimeZone.getTimeZone ( "Asia/Seoul" ) );

return sdf4.format ( now );
}
------------------------------------------------------------------

날짜와 시간이 유효한지 검사하려면...?
------------------------------------------------------------------
import java.util.*;
import java.text.*;

public class DateCheck
{
boolean dateValidity = true;

DateCheck ( String dt )
{
try
{
DateFormat df = DateFormat.getDateInstance ( DateFormat.SHORT );
df.setLenient ( false );
Date dt2 = df.parse ( dt );
}
catch ( ParseException e ) { this.dateValidity = false; }
catch ( IllegalArgumentException e ) { this.dateValidity = false; }
}

public boolean datevalid ( )
{
return dateValidity;
}

public static void main ( String args [] )
{
DateCheck dc = new DateCheck ( "2001-02-28" );
System.out.println ( " 유효한 날짜 : " + dc.datevalid ( ) );
}
}
------------------------------------------------------------------

두 날짜 비교하기(아래보다 정확)
------------------------------------------------------------------
그냥 날짜 두개를 long(밀리 세컨드)형으로 비교하시면 됩니다...

이전의 데이타가 date형으로 되어 있다면, 이걸 long형으로 변환하고.
현재 날짜(시간)은 System.currentTimeMillis()메소드로 읽어들이고,
두수(long형)를 연산하여 그 결과 값으로 비교를 하시면 됩니다.

만약 그 결과값이 몇시간 혹은 며칠차이가 있는지를 계산할려면,
결과값을 Calender의 setTimeInMillis(long millis) 메소드를 이용해
설정한다음 각각의 날짜나 시간을 읽어오시면 됩니다
------------------------------------------------------------------

두 날짜 비교하기2
------------------------------------------------------------------
//Calendar를 쓸 경우 데이타의 원본을 고치기 때문에 clone()을 사용하여
//복사한 후에 그 복사본을 가지고 비교한다
import java.util.*;
import java.util.Calendar.*;
import java.text.SimpleDateFormat;

public class DayComparisonTest
{
public static void main(String args[])
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateForm = new SimpleDateFormat("yyyy-MM-dd");

Calendar aDate = Calendar.getInstance(); // 비교하고자 하는 임의의 날짜
aDate.set(2001, 0, 1);

Calendar bDate = Calendar.getInstance(); // 이것이 시스템의 날짜

// 여기에 시,분,초를 0으로 세팅해야 before, after를 제대로 비교함
aDate.set( Calendar.HOUR_OF_DAY, 0 );
aDate.set( Calendar.MINUTE, 0 );
aDate.set( Calendar.SECOND, 0 );
aDate.set( Calendar.MILLISECOND, 0 );

bDate.set( Calendar.HOUR_OF_DAY, 0 );
bDate.set( Calendar.MINUTE, 0 );
bDate.set( Calendar.SECOND, 0 );
bDate.set( Calendar.MILLISECOND, 0 );


if (aDate.after(bDate)) // aDate가 bDate보다 클 경우 출력
System.out.println("시스템 날짜보다 뒤일 경우 aDate = " + dateForm.format(aDate.getTime()));
else if (aDate.before(bDate)) // aDate가 bDate보다 작을 경우 출력
System.out.println("시스템 날짜보다 앞일 경우 aDate = " + dateForm.format(aDate.getTime()));
else // aDate = bDate인 경우
System.out.println("같은 날이구만");
}
}

+ Recent posts