( Android에서 현재 시간 알기 )


[MainActivity.java]

import java.util.Date;


public class MainActivity extends Activity {

TextView timeView;

long now_Time = System.currentTimeMillis();

Date date = new Date(now_Time);

//날짜, 시간정보 받아오기

SimpleDateFormat CurDateFormat = new SimpleDateFormat("yyyy년 MM월 dd일");

SimpleDateFormat CurTimeFormat = new SimpleDateFormat("HH시 mm분");

SimpleDateFormat CurYearFormat = new SimpleDateFormat("yyyy");

SimpleDateFormat CurMonthFormat = new SimpleDateFormat("MM");

SimpleDateFormat CurDayFormat = new SimpleDateFormat("dd");

SimpleDateFormat CurHourFormat = new SimpleDateFormat("HH");

SimpleDateFormat CurMinuteFormat = new SimpleDateFormat("mm");


//위에서 지정된 포맷으로, String 타입으로 리턴합니다.

String strCurDate = CurDateFormat.format(date);

String strCurTime = CurTimeFormat.format(date);

String strCurYear = CurYearFormat.format(date);

String strCurMonth = CurMonthFormat(date);

String strCurDay = CurDayFormat.format(date);

String strCurHour = CurHourFormat.format(date);

String strCurMinute = CurMinuteFormat.format(date);


/* 위와 같이 MainActivity에서 날짜 및 시간에 대한 정보를 얻을 수 있습니다.

만약 TextView에서 위의 정보를 이용하여 보여주고 싶다면, 아래와 같이 setText를 통해 월, 일, 시간에 대한 정보를 볼 수 있게 됩니다. */


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);


timeView = (TextView)findViewById(R.id.txt_curTime(보여줄 TextView의 id));

timeView.setText("현재 시간정보 = " + strCurMonth + "월 " + strCurDay + "일 " + strCurHour + "시");

}


////////////////////////////////////////////////////////////////////////////////////

[activity_main.xml]

<TextView

android:id="@+id/txt_curTime"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:textSize="12dp" />


이 소스에서는 TextView를 하나 만들어 준 후, MainActivity에서 사용하기 위하여 android.id를 txt_curTime 으로 해주면 됩니다. id만 추가하면 됩니다.


WRITTEN BY
SiriusJ

,