通过Android获得GMT时间

Day*_*man 14 android date-format gmt

我一直在StackOverflow Android中获取当前UTC时间, 并且 如何在Java中获取UTC或GMT中的当前日期和时间?

我尝试了两种方法来获取GMT手机的当前时间.我在西班牙,区别是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();
Run Code Online (Sandbox Code Playgroud)

我需要将那个时间减去另一个时间,这就是为什么我将演员阵容变为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 ;
Run Code Online (Sandbox Code Playgroud)

我也试过这个:

    Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()
Run Code Online (Sandbox Code Playgroud)

而且我仍然没有得到正确的区别.但如果我这样做:

    Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()-3600000*2;
Run Code Online (Sandbox Code Playgroud)

它确实有效.

有任何想法吗?

非常感谢,

大卫.

nit*_*ddy 23

这肯定有用!

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

指定格式,您将在GMT中获得它!


Vad*_*ade 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);
Run Code Online (Sandbox Code Playgroud)

看看是否可行。


小智 5

据我读到calendar.getTimeInMillis(); 以毫秒为单位返回UTC时间.我使用以下代码并将其与本网站http://www.xav.com/time.cgi中的Epoch进行了比较.

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

}
Run Code Online (Sandbox Code Playgroud)

Giora

  • -1:`getInstance()`明确指出:"构造一个适用于默认语言环境和默认TimeZone的Calendar子类的新实例." 可能是`Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis()`会更好用 (5认同)