2017-10-11 49 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到系統時間的本地時間之間的偏移量,以更正系統時間(如果需要)。 –