2013년 10월 6일 일요일

자바 날짜계산

시스템의 밀리초 구하기.(국제표준시각(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("같은 날이구만"); } }

2013년 9월 27일 금요일

온라인 IDE(웹통합개발자환경, WIDE) 모음


Cloud9 IDE

ideone.com

wiode

ShiftEdit

compilr

coderun

Cloud IDE

sourceLair

codeanywhere

Kodingen

codepad

heroku

neptunIDE

SrIde

PLAY MY CODE

Codeacademy

Codeacademy<labs>

pythonanywhere

Akshell

beanstalk

neutron ide

weecod

tmpltr

try jasmine!

codeblender

ShareLaTex

Mini Web IDE for IronPython and Silverlight 2

Python Fiddle

uizard

wonderfl

ZOHO Creator

ECCO

Krazy Koder

Py I/O

Try Python

codenode

Interactive server-side Python shell for Google App Engine

repl.it

Rendera

HTMLEditor.in

Maqetta

CSSDesk

WebPutty

CSSMate

Cssizer



JS Bin

N2J.com

PractiCode

erbix JS App Editor

WriteCodeOnline.com

편집기

Amy Editor

EditPad.org

typeit

9ne

jsvi

Real-time HTML Editor

DARKCOPY

---
2012.10.25. 

Codepen

2013년 9월 10일 화요일

앱을 만들다 보면 인텐트를 통해 단순히 String, int, boolean 같은 기본 타입 뿐 아니고 커스텀 클래스나 오브젝트를 다른 컴포넌트에 전달해 줘야 할 경우가 많다. 그 경우 단순히 그냥 인텐트에 putExtra() 로는  넣어줄 수가 없다.
안드로이드에서는 그런 경우를 위해 자바의 Serialization 개념과 유사한 Parcelable이라는 클래스가 있다.

먼저 이런것이 왜 필요한가 살펴보겠다. 예를 들어 다음과 같은 클래스가 있다고 하자.

public class BookData {
  int _id;
  String title;
  String author;
  String publisher;
  int price;
}

도서관리 앱에서 ListView로 화면에 표시하기 위해 ArrayList<BookData>에 책들의 정보를 넣어 인텐트로 넘겨주려고 하면 BookData 클래스를 그대로 사용할수는 없다. 

오브젝트를 Parcelable 클래스로 만들어 주려면 android.os.Parcelable 인터페이스를 구현해야 한다. 그러므로 아래와 같이 클래스 정의를 변경한다.

public class BookData implements Parcelable {
  int _id;
  String title;
  String author;
  String publisher;
  int price;
}

그리고 android.os.Parcelable 인터페이스에 있는 2개의 메소드를 오버라이드 해 줘야만 한다. 

describeContents() - Parcel 하려는 오브젝트의 종류를 정의한다.
writeToParcel(Parcel dest, int flags) - 실제 오브젝트 serialization/flattening을 하는 메소드. 오브젝트의 각 엘리먼트를 각각 parcel해줘야 한다.

public void writeToParcel(Parcel dest, int flags) {
  dest.writeInt(_id);
  dest.writeString(title);
  dest.writeString(author);
  dest.writeString(publisher);
  dest.writeInt(price);
}

다음으로 해야 할 일은 Parcel에서 데이터를 un-marshal/de-serialize하는 단계를 추가해줘야 한다. 그러기 위해서 Parcelable.Creator 타입의 CREATOR라는 변수를 정의해야 한다. 이 변수를 정의하지 않으면 안드로이드는 다음과 같은 익셉션을 발생한다.

Parcelable protocol requires a Parcelable.Creator object called CREATOR

아래는 위의 예제인 BookData 클래스를 위한 Parcelable.Creator<BookData>의 코드이다.

public class CustomCreator implements Parcelable.Creator<BookData> {
  public BookData createFromParcel(Parcel src) {
    return new BookData(src);
  }

  public BookData[] newArray(int size) {
    return new BookData[size];
  }
}

BookData.java에 모든 parcel된 데이터를 복구하는 생성자를 정의해 줘야만 한다.

  public BookData(Parcel src) {
    _id = src.readInt();
    title = src.readString();
    author = src.readString();
    publisher = src.readString();
    price = src.readInt();
  }

주의할것은 writeToParcel() 메소드에서 기록한 순서와 동일하게 복구해야만 한다.

전체 코드는 다음과 같다.

...
public class BookData implements Parcelable {
    private String title;
    private String author;
    private String publisher;
    private String isbn;
    private String description;
    private int price;
    private String photoUrl;
   
    public BookData() {
    }
   
    public BookData(Parcel in) {
       readFromParcel(in);
    }

    public BookData(String _title, String _author, String _pub, String _isbn, String _desc, int _price, String _photoUrl) {
         this.title = _title;
         this.author = _author;
         this.publisher = _pub;
         this.isbn = _isbn;
         this.description = _desc;
         this.price = _price;
         this.photoUrl = _photoUrl;
    }

// -------------------------------------------------------------------------
// Getters & Setters section - 각 필드에 대한 get/set 메소드들
// 여기서는 생략했음

// ....
// ....
// -------------------------------------------------------------------------
   

   public void writeToParcel(Parcel dest, int flags) {
           dest.writeString(title);
           dest.writeString(author);
           dest.writeString(publisher);
           dest.writeString(isbn);
           dest.writeString(description);
           dest.writeString(photoUrl);
           dest.writeInt(price);
   }

   private void readFromParcel(Parcel in){
           title = in.readString();
           author = in.readString();
           publisher = in.readString();
           isbn = in.readString();
           description = in.readString();
           photoUrl = in.readString();
           price = in.readInt();
   }
   
   public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public BookData createFromParcel(Parcel in) {
             return new BookData(in);
       }

       public BookData[] newArray(int size) {
            return new BookData[size];
       }
   };
}

Parcelable 오브젝트를 인텐트로 보내는 경우는 다음과 같이 하면 된다.

BookData book = new BookData();
// 각 필드에 값을 넣어줌

Intent i = new Intent(this, ShowBook.class);
i.putExtra("bookInfo", book);
startActivity(i);

인텐트를 받을 ShowBook.java에서는 다음과 같이 Parcelable 오브젝트를 복구하면 된다.

Bundle bundle = getIntent().getExtras();
BookData book = bundle.getParcelable("bookInfo");

ArrayList<BookData>인 경우는 Intent를 만들어 보내는 쪽에서는 다음과 같이 하면 된다.

ArrayList<BookData> bookList = new ArrayList<BookData>();
...
// bookList.add() 메소드를 사용해서 bookList에 BookData 엔트리를 추가
...

Intent i = new Intent(this, BookList.class);
i.putParcelableArrayListExtra("myBooks", bookList);
startActivity(i);

BookList.java (인텐트에 의해 호출되는 액티비티)에서는 다음과 같이 오브젝트를 복구하면 된다.

ArrayList<BookData> bookList;
...
Intent i = getIntent();
bookList = i.getParcelableArrayListExtra("myBooks");