2017-10-11 47 views
1

我尝试用下面的公式得到Location.getTime()本地时间:GPS位置和本地时间

long localTime = location.getTime() + Calendar.getInstance().getTimeZone().getOffset(Calendar.ZONE_OFFSET); 

;

但我在不同的Android版本和不同的模拟器上获得不同的时间。我怎样才能始终获得正确的时间?

完整的代码是:

private final long TimeOffset = Calendar.getInstance().getTimeZone().getOffset(Calendar.ZONE_OFFSET); 
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); 
    locationlistener = new LocationListener() { 
     @Override 
     public void onLocationChanged(Location location) { 
      boolean wasNull = locFine == null; 
      if (location.getProvider().equals(android.location.LocationManager.GPS_PROVIDER)) { 
       locFine = location; 
       //long TimeOffset = Calendar.getInstance().getTimeZone().getRawOffset(); 
       long gpsTime = locFine.getTime() + TimeOffset; 
       long SystemTime = Calendar.getInstance().getTimeInMillis(); 
       timeOffsetGPS = gpsTime - SystemTime; 
       Date dtgps = new Date(locFine.getTime()); 
       Log.d("Location", "Time GPS: " + dtgps); // This is what we want! 
       if (context != null && a != null) { 
        if (wasNull) lib.ShowToast(a, getString(R.string.gotGPS)); 
        /* 
        lib.ShowMessage(a,"gps time: " + dtgps 
          + "\nsystem time: " + new Date(SystemTime) 
          + "\noffset: " + timeOffsetGPS/1000 
          + "\ncorrected gpstime: " + new Date(gpsTime)); 
        */ 
       } 

      } 

     } 

     @Override 
     public void onStatusChanged(String s, int i, Bundle bundle) { 
      if (a != null) lib.ShowToast(context, context.getString(R.string.gpsstatus) + " " + s); 
     } 

     @Override 
     public void onProviderEnabled(String s) { 
      if (context != null) lib.ShowToast(context, s + " " + getString(R.string.enabled)); 
     } 

     @Override 
     public void onProviderDisabled(String s) { 
      if (context != null) 
       lib.ShowMessage(context, s + " " + getString(R.string.disabled)); 
     } 
    }; 
    try { 
     if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
      locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, 1000, 5, locationlistener);} 

回答

0

从位置类的的getTime()方法的文档,在https://developer.android.com/reference/android/location/Location.html

返回此修复UTC时间(毫秒),因为1970年1月1日。

所以,在你的onLocationChanged()方法中,你可以得到一个像这样的Date对象,它表示当th获得E位置定位(你在你的代码的中间确实有这个在一个点):

Date fixDateTime = new Date(location.getTime()); 

由于Date对象存储日期/时间内为UTC,你可以使用任何的日期/时间格式化功能可以在相关的任何时区显示该时间戳。您不需要添加或减去任何偏移量。

如果您不熟悉日期/时间格式化函数,请首先阅读SimpleDateFormat文档https://developer.android.com/reference/java/text/SimpleDateFormat.html

+0

我知道location.getTime()通常会得到UTC时间,但我不需要格式化的日期,但本地时间以毫秒为单位。当然,我可以再次解析格式化的日期以获取当地时间,但这不会非常有效。 –

+0

你想在当地时间做什么?这些信息可能有助于给出更好的答案。 –

+0

我想计算从gps到系统时间的本地时间之间的偏移量,以更正系统时间(如果需要)。 –