Android location getTime() always returns big diff

2019-02-25 01:10发布

I am getting location using Location Manager regulary depending on the setting, 2minutes in testing case and trying to use location.geTime() method. I am not using LocationManager.getLastKnownLocation(). Document says it is UTC time and I converted it to local time like below:

Date d = new Date(location.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddkkmmss';
sdf.setTimeZone(TimeZone.getTimneZone("UTC");
sdf.format(d);

But I am getting different date from what I expect. Current time I am writing is about 130516155000(2013-05-16 15:50:00) but I am getting 040015130515. And I removed the timezone and set the time zone as 'GMT' as well and date fixed but time was quite different. In real device and emulator are same. And I already checked timezone setting in both and they are correct. Please tell me what I am missing?

Thanks.

EDIT:

I add more.

Log:
05-16 16:09:30.227: D/location.getTime()(1279): 1368590417000
05-16 16:09:30.237: D/NMEAGPRMCTime(1279): 040017
05-16 16:09:30.247: D/NMEAGPRMCDate(1279): 130515

Code:

public static String NMEAGPRMCTime(Date d)
{
    SimpleDateFormat sdf = new SimpleDateFormat("kkmmss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String result = sdf.format(d);
    Log.d("NMEAGPRMCTime", result);
    return result;
}


public static String NMEAGPRMCDate(Date d)
{
    SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String result = sdf.format(d);
    Log.d("NMEAGPRMCDate", result);

    return result;
}

That's it. This is the code exactly what I using.

1条回答
乱世女痞
2楼-- · 2019-02-25 01:47

There's absolutely nothing wrong with the formatting here.

Look at the log:

05-16 16:09:30.227: D/location.getTime()(1279): 1368590417000
05-16 16:09:30.237: D/NMEAGPRMCTime(1279): 040017
05-16 16:09:30.247: D/NMEAGPRMCDate(1279): 130515

Using epochconverter you can see that the "millis since epoch" value of 1368590417000 is actually Wed, 15 May 2013 04:00:17 UTC. So a time of 040017 and a date of 130515 is exactly right.

I suspect you're actually confused by what Location.getTime() does - it returns the time of the fix, not the current time. So basically, that location was obtained at 04:00:17 UTC, regardless of the current date/time.

查看更多
登录 后发表回答