16

StackOverflow Android get Current UTC timeHow can I get the current date and time in UTC or GMT in Java? でしばらくの間、質問を掘り下げてきました 。

携帯電話の現在時刻を GMT で取得する方法を 2 つ試しました。私はスペインにいますが、差は GMT+2 です。それでは例を見てみましょう: 1º 試み: フォーマットを作成し、それを System.currentTimeMillis();

    DateFormat dfgmt = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");   
    dfgmt.setTimeZone(TimeZone.getTimeZone("GMT")); 
    String gmtTime = dfgmt.format(new Date());
    //Using System.currentTimeMillis() is the same as new Date()
    Date dPhoneTime = dfgmt.parse(gmtTime);
    Long phoneTimeUTC = dPhoneTime.getTime();

その時間を別の時間に差し引く必要があるため、Long にキャストします。

    DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");          
    Date arrivalDate = df.parse(item.getArrivalDate());
    //the String comes from JSON and is for example:"UTC_arrival":"2011-05-16 18:00:00"
    //which already is in UTC format. So the DateFormat doesnt have the GMT paramater as dfgmt
    diff = arrival.getTime() - phoneTimeUTC ;

私もこれを試しました:

    Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()

それでも、正しい違いがわかりません。しかし、私がこれを行うと:

    Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()-3600000*2;

それは正常に動作します。

何か案は?

どうもありがとう、

デビッド。

4

6 に答える 6

26

これは確かに機能します!

        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
        System.out.println(dateFormatGmt.format(new Date())+"");

フォーマットを指定すると、GMT で取得されます。

于 2012-04-17T06:37:02.483 に答える
5
     Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
     Date currentLocalTime = cal.getTime();
     DateFormat date = new SimpleDateFormat("dd-MM-yyy HH:mm:ss z");   
     date.setTimeZone(TimeZone.getTimeZone("GMT")); 
     String localTime = date.format(currentLocalTime); 
     System.out.println(localTime);

見て、それが機能するかどうかを確認してください。

于 2011-05-16T08:56:18.057 に答える
5

私がcalendar.getTimeInMillis();を読んだ限り UTC時間をミリ秒で返します。次のコードを使用して、このサイトhttp://www.xav.com/time.cgiのエポックと比較しました。

public int GetUnixTime()
{
    Calendar calendar = Calendar.getInstance();
    long now = calendar.getTimeInMillis();
    int utc = (int)(now / 1000);
    return (utc);

}

ジョラ

于 2011-05-31T07:07:26.510 に答える
1

出力: 2016-08-01 14:37:48 UTC

    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

正常に動作します。

于 2016-08-03T09:24:42.703 に答える