各国対応の現在時刻の表示 | Notation of current time | Android Java

スポンサーリンク
スポンサーリンク

SimpleDateFormatを使って表記

世界対応のアプリをリリースする際にはいくつか注意すべき点があります。

その一つが日時の表現です。

大きく3つあり、ヨーロッパ式(英国式)、アメリカ式、日本式です。

ではどのような表記でしょうか。

ヨーロッパ式 日/月/年  時/分/秒

アメリカ   月/日/年 時/分/秒

日本     年/月/日 時/分/秒

となります。アメリカ式は実際のところアメリカで使われているのみですから、

デフォルトはヨーロッパ式として、アメリカ、日本の場合のみ変更とするのが良いでしょう。

DateFormatを使えば簡単に表記することができます。

ではif文で記述してみましょう

DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Locale locale = Locale.getDefault();
if(locale.equals(Locale.JAPAN)){
    df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}else if(locale.equals(Locale.US)){
    df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
}

これだけです。

そして、実際の現在時刻を取得して、このフォーマットを当てます。

Date date = new Date(System.currentTimeMillis()); Log.d(“Log0”,df.format(date))

となります。

ソースコード

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        Locale locale = Locale.getDefault();
        if (locale.equals(Locale.JAPAN)) {
            df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        } else if (locale.equals(Locale.US)) {
            df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        }
        Date date = new Date(System.currentTimeMillis());

        Log.d("Log0", df.format(date));
    }
}

時間を12時間表記に

DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

の部分を

DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

とします。 HH → hh です。

これで12時間表記となります。

午前・午後の表記

午前午後の表記をする際は, “a” を用います。

DateFormat df = new SimpleDateFormat("yyyy/MM/dd ah:mm:ss");

英語表記ではご10時を 10 amのようにかきますので

DateFormat df = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");

とします。