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);}
我知道location.getTime()通常会得到UTC时间,但我不需要格式化的日期,但本地时间以毫秒为单位。当然,我可以再次解析格式化的日期以获取当地时间,但这不会非常有效。 –
你想在当地时间做什么?这些信息可能有助于给出更好的答案。 –
我想计算从gps到系统时间的本地时间之间的偏移量,以更正系统时间(如果需要)。 –