« Android MarketのCopy Protection動作 | メイン | Android 日付フォーマット »

Android 時間フォーマット

Androidでは、ユーザーが時間のフォーマットが指定でき、 プログラム側では、これらのフォーマットを参照して画面に出力する必要がある。

時間表示フォーマットは、Setting - Date & Time - Use 24-hour formatにて設定をする。

時間表示フォーマットは、12時間表記か24時間表記かのどちらかとなる。

ユーザーにより設定されたフォーマットは、Settings.System.getStringメソッドの引数に、Settings.System.TIME_12_24を渡すことで取得可能。

注意点

  • 時間フォーマットは、12か24かの文字列を返す。

サンプルコード


	/**
	 * 時間フォーマットを返す。
	 * 
	 * Setting - Date & Time - Use 24-hour formatで設定された値を取得する。
	 * @param ctx  the application context
	 * @return 
	 */
	public static final String getTimeFormatPattern(Context ctx){
	    final String HOURS_24 = "24";
	    final String PATTERN_24 = "H:mm";
	    final String PATTERN_12 = "h:mm a";
	    
	    String value = Settings.System.getString(ctx.getContentResolver(),Settings.System.TIME_12_24);
	    if(HOURS_24.equals(value))  	return PATTERN_24;
        else							        	return PATTERN_12;
	}
	/**
	 * 時間のSimpleDateFormatを返す。
	 * 
	 * Setting - Date & Time - Select date formatで設定された値をSimpleDateFormatで返す。 
	 * @param ctx  the application context
	 * @return the {@link java.text.DateFormat} object
	 */
	public static final SimpleDateFormat getTimeFormat(Context ctx){
        	return new SimpleDateFormat(getTimeFormatPattern(ctx));
	}

ブログ内の関連する記事

  1. Android 日付フォーマット

トラックバック

このエントリーのトラックバックURL:
http://www.taosoftware.co.jp/mt/mt-tb.cgi/161