20

私はAndroidが初めてで、現在タイムゾーンを指定して現在の時刻を取得するという問題に直面しています。

「GMT-7」、つまり文字列の形式でタイムゾーンを取得します。システム時刻があります。

上記のタイムゾーンで現在の時刻を取得するきれいな方法はありますか? どんな助けでも大歓迎です。ありがとう、

編集:これをしようとしています:

public String getTime(String timezone) {
    Calendar c = Calendar.getInstance();
    c.setTimeZone(TimeZone.getTimeZone(timezone));
    Date date = c.getTime();
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    String strDate = df.format(date);
    return c.getTime().toString();
}
4

11 に答える 11

23

私はそれを次のように動作させました:

TimeZone tz = TimeZone.getTimeZone("GMT+05:30");
Calendar c = Calendar.getInstance(tz);
String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
            String.format("%02d" , c.get(Calendar.MINUTE))+":"+
.                   String.format("%02d" , c.get(Calendar.SECOND))+":"+
    .           String.format("%03d" , c.get(Calendar.MILLISECOND));

また、この日付に基づく他のすべての時間変換もこのタイムゾーンで使用する必要があります。そうしないと、デバイスのデフォルトのタイムゾーンが使用され、そのタイムゾーンに基づいて時間が変換されます。

于 2013-04-24T23:34:56.467 に答える
13
// Backup the system's timezone
TimeZone backup = TimeZone.getDefault();

String timezoneS = "GMT-1";
TimeZone tz = TimeZone.getTimeZone(timezoneS);
TimeZone.setDefault(tz);
// Now onwards, the default timezone will be GMT-1 until changed again

Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String timeS = String.format("Your time on %s:%s", timezoneS, date);
System.out.println(timeS);

// Restore the original timezone
TimeZone.setDefault(backup);
System.out.println(new Date());
于 2013-04-24T22:03:50.800 に答える
9

タイムゾーンをカレンダーではなくフォーマッターに設定します。

public String getTime(String timezone) {
    Calendar c = Calendar.getInstance();
    Date date = c.getTime(); //current date and time in UTC
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    df.setTimeZone(TimeZone.getTimeZone(timezone)); //format in given timezone
    String strDate = df.format(date);
    return strDate;
}
于 2015-05-13T10:00:57.170 に答える
8

これを試して:

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(TimeZone.getTimeZone("YOUR_TIMEZONE"));
String strDate = df.format(date);

YOUR_TIMEZONE は、GMT、UTC、GMT-5 などです。

于 2013-04-24T22:01:39.530 に答える