2016-07-16 10 views
0

エキスパート 私は、グローバルな使用のために、指定されたタイムゾーンで現在の日時を取得したいと考えています。クラスメンバーに.setTimeZoneを使用する方法?

したがって、 私は以下のようなクラスを作成しますが、df.setTimeZoneステートメントの構文エラーを示しています。これを達成するためのすてきな方法は何ですか?具体的には、ローカル変数ではなくクラスメンバーのtimezoneプロパティを設定したいと思います。

私は、SimpleDateFormatを通して多くの日付フォーマットを定義しました。どのようにそれらのタイムゾーンを指定するのですか? (.setTimeZoneは1つの日付形式のみたいです)ありがとう。

public class Global { 

static SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 

df.setTimeZone(TimeZone.getTimeZone("GIVEN_TIMEZONE")); 

static String strDate = df.format(new Date()); 

} 

答えて

1

あなたは絶対にあなたは、コードを必要とする、staticフィールドでそれを行う必要がある場合staticイニシャライザブロック:

class Global { 

    static SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 
    static { 
     df.setTimeZone(TimeZone.getTimeZone("GIVEN_TIMEZONE")); 
    } 
    static String strDate = df.format(new Date()); 

} 

UPDATE

あなたがそのように行うには、日付がたくさんある場合は、異なる日付形式および/またはタイムゾーンでは、ヘルパーメソッドを使用する方が良いかもしれません。

class Global { 

    static String strDate = format(new Date(), "dd/MM/yyyy", "GIVEN_TIMEZONE"); 

    private static String format(Date date, String format, String timeZoneID) { 
     SimpleDateFormat df = new SimpleDateFormat(format); 
     df.setTimeZone(TimeZone.getTimeZone(timeZoneID)); 
     return df.format(date); 
    } 

} 
+0

いいね。どうもありがとう!しかし、私は非常に多くのSimpleDateFormatを持っているので、それらを1つずつ設定する必要がありますか? – caibirdcnb

+0

はい、どうして "とてもたくさん"いるのですか? – Andreas

+0

うん、それほど多くない、約12のフォーマット、私はちょうどそれらがすべてより多くの猶予を設定することができると思った... – caibirdcnb

0

可能な構文の下で試してみてください:

String dtc = "2014-04-02T07:59:02.111Z"; 
SimpleDateFormat readDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 
readDate.setTimeZone(TimeZone.getTimeZone("GMT")); // Important line 
Date date = readDate.parse(dtc); 

SimpleDateFormat writeDate = new SimpleDateFormat("dd.MM.yyyy, HH.mm"); 
writeDate.setTimeZone(TimeZone.getTimeZone("GMT+04:00")); // Important line 
String s = writeDate.format(date); 

あなたはクラスの下にインポートする必要があります。 https://developer.android.com/reference/java/util/TimeZone.html

関連する問題