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

안드로이드에서 날짜와 시간 형식을 지정하는 방법 — SimpleDateFormat 활용 가이드

안드로이드에서 날짜와 시간 형식 지정하기

이 예제는 SimpleDateFormat 클래스를 사용하여 안드로이드 앱에서 날짜와 시간을 원하는 형식으로 표시하는 방법을 단계별로 설명합니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project 메뉴로 이동한 뒤, 안내에 따라 필요한 정보를 모두 입력하여 새 프로젝트를 만듭니다.

2단계 — 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:textSize="16sp"
        android:textStyle="bold|italic"
        android:layout_centerInParent="true" />
</RelativeLayout>

3단계 — MainActivity 코드 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    String dateTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MMM-yyyy hh-mm-ss a");
        dateTime = simpleDateFormat.format(calendar.getTime());
        textView.setText(dateTime);
    }
}

위 코드에서 사용된 날짜 패턴 "EEEE, dd-MMM-yyyy hh-mm-ss a"의 각 요소는 다음과 같은 의미를 가집니다.

  • EEEE : 요일 전체 표기 (예: 화요일)
  • dd : 날짜(일)
  • MMM : 월의 축약 표기
  • yyyy : 연도(4자리)
  • hh-mm-ss : 시-분-초
  • a : 오전/오후 구분 표시

4단계 — AndroidManifest.xml 설정

androidManifest.xml 파일에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래 이미지처럼 형식화된 날짜와 시간이 표시됩니다.

안드로이드에서 날짜와 시간 형식을 지정하는 방법 — SimpleDateFormat 활용 가이드

추가 팁 — 최신 날짜/시간 API(java.time) 활용

API 26(안드로이드 8.0) 이상에서는 java.time 패키지의 LocalDateTimeDateTimeFormatter 사용이 권장됩니다. 스레드 안전성이 뛰어나고 API가 직관적이므로, 신규 프로젝트에서는 SimpleDateFormat 대신 java.time 기반의 포맷팅을 고려해 보는 것이 좋습니다.