获取GMT时间与Android时间、GMT、Android

2023-09-12 08:11:27 作者:莫忘i

我一直挖到这个问题在计算器一段时间 的Andr​​oid获取当前UTC时间 和 How我可以得到当前的日期和时间,UTC或GMT在Java中?

I have been digging into the question for a while in StackOverflow Android get Current UTC time and How can I get the current date and time in UTC or GMT in Java?

我已经尝试了两种方式让我的手机在格林尼治标准​​时间的当前时间。我在西班牙不同的是GMT + 2。因此,让我们用一个例子看看: 1º学尝试:我创建了一个格式,并将其应用到System.currentTimeMillis的();

I have tried two ways to get the current time of my phone in GMT. I am in Spain and the difference is GMT+2. So let's see with an example: 1º attemp: I created a format and applied it to 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();

我要substract那个时候另一个时间,这就是为什么我做投龙。

I need to substract that time to another time, that's why i do the cast to 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 ;

我也试过这样的:

I also tried this:

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

和我仍然没有得到正确的区别。但是,如果我这样做:

And still I dont get the right difference. But if I do this:

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

它的工作确定。

It does work OK.

任何想法?

感谢了很多,

大卫。

推荐答案

据我读calendar.getTimeInMillis();返回米利斯UTC时间。我用下面的code和比较它的时代在这个网站 HTTP://www.xav。 COM / time.cgi 。

As far as I read the calendar.getTimeInMillis(); returns the UTC time in millis. I used the following code and compared it to the Epoch in this site http://www.xav.com/time.cgi.

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

}

Giora

Giora