이 튜토리얼에서는 Java의 OffsetTime API 클래스를 사용해 Android 앱에서 현재 시(hour), 분(minute), 초(second)를 가져와 화면에 표시하는 방법을 알아봅니다.
OffsetTime은 Java 8부터 도입된 java.time 패키지의 클래스로, UTC/Greenwich 기준 오프셋이 포함된 시간을 다룰 수 있어 시간대 정보가 필요한 앱에서 유용하게 활용됩니다.
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.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) {
OffsetTime offset = OffsetTime.now();
textView.setText(String.valueOf(offset.getHour() + " : " + offset.getMinute() + " : " + offset.getSecond()));
}
}
}코드 설명
- OffsetTime.now(): 현재 기기의 시간대 오프셋이 포함된 현재 시간을 가져옵니다.
- getHour(), getMinute(), getSecond(): 각각 시, 분, 초 값을 정수 형태로 반환합니다.
- SDK_INT 버전 체크: java.time 패키지는 Android 8.0(API 26, Oreo)부터 지원되므로, 하위 버전에서 크래시가 발생하지 않도록 Build.VERSION_CODES.O 이상인 경우에만 실행하도록 처리했습니다.
4단계 — 앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 모바일 기기를 선택하면, 연결된 기기의 화면에 아래와 같은 결과가 표시됩니다.

위 결과에서 볼 수 있듯이, 화면에는 현재 시, 분, 초가 정상적으로 출력됩니다. 이처럼 OffsetTime 클래스를 활용하면 시간대 오프셋 정보까지 포함된 정확한 현재 시각을 손쉽게 가져올 수 있습니다.