2016-04-27 17 views
1

投稿のタイミング情報を取得できるアプリを開発しています。ロケール設定に基づいて日付を表示する

私が望むのは、ユーザーフレンドリーにするためにミリオンで時刻を表示することですが、私はアンドロイドデバイスの設定で定義された日付の形式に注意する必要があります。私はフォーマットを決定することができるよとき場合

それはDD/MM/YYYYまたはYYYY/MM/DDまたはYYYY/DD/MM

だ、私はちょうど一日と月を取得する必要があります。年は役に立たない

私は以下のコードを行っているが、1月2日は1/2になる場合にはtweetsCreatedTimeが長いとミリ秒と規定されている

DateFormat.getDateInstance(DateFormat.SHORT).format(new Date(tweetsCreatedTime)).substring(0,5) 

を働いていないので、私は、私は部分文字列を使用しているという事実が好きではありません

ローカルを使用する代わりに、設定を取得し、ローカルにENまたはUSが表示されている場合でも、ユーザーは表示方法を変更しないようにしてください。

おかげ

答えて

1

java.text.DateFormat dateFormat = DateFormat.getTimeFormat(context); 
String dateString = dateFormat.format(date); 

は、それはまたjava.text.DateFormatという名前のクラスを返しますが、それは異なるクラスだ覚えておいてください。

0
それは使用が、ここでデバイスの設定に関係なく、任意の日付を使用して独自のフォーマットを使用することができSimpleDateFormater

こんにちは使用することは、私はすべての時間を使用するカスタムメソッドも、あなたはそれを表示したいウィッヒローカルを設定することができますです日付

/** 
* Get localized date string (Using given locale) 
* 
* @param dateString Date string 
* @param locale  Desired locale 
* @return Formatted localized date string 
*/ 
public static String formatLocalized(String dateString, Locale locale) { 
    Date date = formatDate(dateString, locale); 
    SimpleDateFormat iso8601Format = new SimpleDateFormat("d MMM yyyy", locale); 
    iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); 
    return iso8601Format.format(date); 

} 

Locale.ENGLISHを使用して、ローカル定義| Locale.FRENCH ...

+0

あなたはSimpleDateFormatでフォーマットを強制します。デバイスの設定からこのフォーマットを取得する方法はありますか? – Seb

+0

デバイスから取得できるものはローカルのwitchが使用されており、その値はLocale.getDefault();ロケールがフランス語の形式で表示されている場合、またはロケールが英語の場合(ほとんどの場合、英語の形式を使用して日付を表示する場合)、日付の表示方法はあなた次第です – thunder413

0

java.time

あなたはMODを使用する必要がありますjava.nimeパッケージのjava.util.Dateクラス。

詳細については、How can I format Date with Locale in Androidとほぼ同じ質問のmy Answerを参照してください。

与えられた入力変数の数値変数longに対して、誤ったノーマーをtweetsCreatedTimeからtweetMillisecondsSinceEpochに変更する簡単なサンプルコードです。あなたの入力はミリ秒単位ですが、java.timeクラスは実際にはナノ秒という非常に細かい分解能が可能です。私はDateFormatを使用

Instant instant = Instant.ofEpochMilli(tweetMillisecondsSinceEpoch); // Number of milliseconds since the POSIX epoch of first moment of 1970 in UTC. 
ZoneId zoneId = ZoneId.of("Pacific/Auckland"); // Arbitrary choice of time zone. Crucial it determining the date, as date varies with a new day dawning earlier to the east. 
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant , zoneId); // Apply a time zone. 
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); // Let java.time translate human language and determine cultural norms in formatting. 
formatter = formatter.withLocale(Locale.CANADA_FRENCH); // Arbitrarily choosing Québec as the Locale. Note that Locale has *nothing* to do with time zone. You could use Chinese locale for a time zone in Finland. 
String output = zdt.format(formatter); // Generate String representation of our date-time value. 

2015年5月23日

関連する問題