Android
 Computer >> コンピューター >  >> プログラミング >> Android

AndroidでISO 8601形式の日付文字列をDateオブジェクトに変換する方法

この記事では、Androidアプリ開発において、ISO 8601形式の日付・時刻文字列をDateオブジェクトに変換する方法を、実際のサンプルコードとともにステップごとに解説します。

手順1:新規プロジェクトの作成

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを生成してください。

手順2:レイアウトファイル(activity_main.xml)の編集

res/layout/activity_main.xmlに以下のコードを記述します。ここでは、画面中央に日付を表示するためのTextViewを配置しています。

<?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"
    android:gravity="center"
    tools:context=".MainActivity">
    <TextView
        android:padding="20sp"
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="12sp"
        android:textStyle="bold"/>
</RelativeLayout>

手順3:MainActivity.javaの編集

src/MainActivity.javaに以下のコードを追加します。SimpleDateFormatを使って、ISO 8601形式の文字列(例:"2019-08-15T09:27:37Z")をDateオブジェクトへパースしています。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        String dtStart = "2019-08-15T09:27:37Z";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        try {
            Date date = format.parse(dtStart);
            textView.setText("ISO 8601 date/time: " + date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

ポイント:ISO 8601の末尾にある「Z」はUTC(協定世界時)を意味します。正確な時刻を扱いたい場合は、format.setTimeZone(TimeZone.getTimeZone("UTC"))のようにタイムゾーンを明示的に設定することをおすすめします。また、APIレベル26以降を対象とする場合は、より安全でモダンなjava.time.OffsetDateTime.parse()の利用も検討してください。

手順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端末がパソコンに接続されているものとして説明します。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。実行デバイスとして自分のモバイル端末を選択すると、端末の画面に変換された日付・時刻が表示されます。

AndroidでISO 8601形式の日付文字列をDateオブジェクトに変換する方法

  1. 【Android開発】カラー整数(int)を16進数カラーコード文字列に変換する方法

    Androidアプリ開発では、色情報がint型の整数値として扱われることが多く、これを「#FF5733」のような16進数のカラーコード文字列に変換したいケースがあります。本記事では、Integer.toHexString()メソッドを使ってカラー整数を16進文字列に変換する方法を、実際のサンプルプロジェクトとともにわかりやすく解説します。変換の仕組みAndroidでは、色はARGB形式(アルファ・赤・緑・青)の32ビット整数として表現されます。そのため、-16895234のような負の値も有効なカラー整数です。Integer.toHexString(int)で16進文字列に変換した後、先頭2桁は

  2. Androidでミリ秒を日付形式に変換する方法【サンプルコード付き】

    この記事では、Androidアプリ開発においてミリ秒(long型のタイムスタンプ)を日付形式に変換する方法を、実際のサンプルコードとともに解説します。ミリ秒から日付への変換には、Java標準のSimpleDateFormatクラスを使用します。非常にシンプルな実装なので、初心者の方でもすぐに理解できるでしょう。実装手順ステップ1:新規プロジェクトを作成するAndroid Studioを開き、「File」⇒「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトのセットアップを完了させてください。ステップ2:レイアウトファイル(activity_