Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 OffsetDateTime API를 활용해 로컬 날짜(Local Date) 가져오는 방법

이 예제에서는 자바의 Offset Date Time API 클래스를 사용하여 안드로이드에서 OffsetDateTime 기반의 로컬 날짜(현재 날짜)를 가져오는 방법을 알아봅니다.

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 하나를 배치했습니다. 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;

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.toLocalDate()));
        }
    }
}

위 코드의 핵심은 다음과 같습니다.
- OffsetDateTime.now(): 현재 시스템 시간대 오프셋이 포함된 현재 날짜와 시간을 가져옵니다.
- offset.toLocalDate(): 오프셋 정보를 제거하고 순수한 로컬 날짜(LocalDate)만 추출합니다.
- Build.VERSION.SDK_INT >= VERSION_CODES.O: java.time 패키지는 Android 8.0(API 26, Oreo)부터 지원되므로 버전 체크가 필요합니다. 하위 버전을 지원하려면 desugaring 또는 ThreeTenABP 라이브러리 사용을 고려할 수 있습니다.

실행 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후 툴바의 Run 아이콘을 클릭합니다. 실행 옵션에서 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같이 결과가 표시됩니다.

안드로이드에서 OffsetDateTime API를 활용해 로컬 날짜(Local Date) 가져오는 방법

위 결과에서 확인할 수 있듯이, 화면에는 현재 로컬 날짜가 정상적으로 출력됩니다. 이처럼 OffsetDateTime 클래스를 활용하면 시간대 오프셋 정보를 포함한 날짜·시간 데이터를 손쉽게 다룰 수 있으며, 필요에 따라 로컬 날짜만 깔끔하게 분리해서 사용자에게 보여줄 수 있습니다.