이 튜토리얼에서는 자바 8에 도입된 OffsetDateTime API 클래스를 활용해 안드로이드에서 일(day of month), 연중 일차(day of year), 요일(day of week)을 구하는 방법을 단계별로 살펴봅니다.
1단계 — 새 프로젝트 생성
Android Studio를 실행한 뒤 File ⇒ New Project 메뉴로 이동하고, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계 — 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Local Date"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>위 코드에서는 일, 연중 일차, 요일 정보를 화면에 표시하기 위해 TextView 하나를 배치했습니다.
3단계 — MainActivity 코드 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다.
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.date);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
OffsetDateTime offset = OffsetDateTime.now();
textView.setText(String.valueOf(offset.getDayOfWeek() + " : " + offset.getDayOfMonth() + " : " + offset.getDayOfYear()));
}
}
}참고: java.time 패키지는 Android 8.0(API 26) 이상에서만 지원되므로, 위 코드에서는 Build.VERSION.SDK_INT 조건문으로 기기의 API 레벨을 먼저 확인한 후 OffsetDateTime을 사용하도록 처리했습니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후 툴바의 Run 아이콘을 클릭하세요. 기기 선택 목록에서 본인의 모바일 기기를 고르면, 기기 화면에 아래와 같은 결과가 표시됩니다.

위 결과에서 현재 요일(getDayOfWeek), 이번 달의 며칠인지(getDayOfMonth), 올해의 몇 번째 날인지(getDayOfYear)가 콜론(:)으로 구분되어 정상적으로 출력되는 것을 확인할 수 있습니다.