2011-02-24 82 views
0

我有以下代碼:TimeZone的基於位置

  mSavedTime = new Time();//????Always returns America/New York 
     double latitude = 40.09596; 
     double longitude = -74.22213; 
     double elevation = 0; 
     TimeZone timeZone = TimeZone.getTimeZone(mSavedTime.timezone); 

我的第一個問題是:我怎麼得到一定緯度\經度組合高程信息? 我的第二個問題是:如何獲得某個lon \ lan組合的timeZone字符串?上面的代碼將提供手機時鐘設置的時區字符串(返回美國/紐約)。我想根據我設置的經緯度得到字符串。

+0

[你想要的一切就是在這個答案](http://stackoverflow.com/questions/41504/timezone-lookup-from-latitude-longitude/41533#41533) – Reno 2011-02-24 03:22:11

回答

-1

晚上好。 我已經爲android創建了應用程序。我用它作爲我的其他應用程序的數據庫。這些功能是: 1)你的手機上有離線的城市數據庫。 2)我創建了廣播接收器API,以便在antoher應用程序中使用它。

cities15000.txt轉換爲數據庫。

這是免費的。你可以使用它,如果你想。我覺得有一些錯誤和界面不好。但它會盡快修復。 鏈接:https://play.google.com/store/apps/details?id=ru.ps.locations 網站:https://sites.google.com/site/applicationlocations/

2

試試這個代碼使用谷歌時區API:

private String get_UTC_Datetime_from_timestamp(long timeStamp){ 

    try{ 

     Calendar cal = Calendar.getInstance(); 
     TimeZone tz = cal.getTimeZone(); 

     int tzt = tz.getOffset(System.currentTimeMillis()); 

     timeStamp -= tzt; 

     // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault()); 
     DateFormat sdf = new SimpleDateFormat(); 
     Date netDate = (new Date(timeStamp)); 
     return sdf.format(netDate); 
    } 
    catch(Exception ex){ 
     return ""; 
    } 
    } 

class NTP_UTC_Time 
{ 
    private static final String TAG = "SntpClient"; 

    private static final int RECEIVE_TIME_OFFSET = 32; 
    private static final int TRANSMIT_TIME_OFFSET = 40; 
    private static final int NTP_PACKET_SIZE = 48; 

    private static final int NTP_PORT = 123; 
    private static final int NTP_MODE_CLIENT = 3; 
    private static final int NTP_VERSION = 3; 

    // Number of seconds between Jan 1, 1900 and Jan 1, 1970 
    // 70 years plus 17 leap days 
    private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L; 

    private long mNtpTime; 

    public boolean requestTime(String host, int timeout) { 
     try { 
      DatagramSocket socket = new DatagramSocket(); 
      socket.setSoTimeout(timeout); 
      InetAddress address = InetAddress.getByName(host); 
      byte[] buffer = new byte[NTP_PACKET_SIZE]; 
      DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT); 

      buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3); 

      writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET); 

      socket.send(request); 

      // read the response 
      DatagramPacket response = new DatagramPacket(buffer, buffer.length); 
      socket.receive(response);   
      socket.close(); 

      mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);    
     } catch (Exception e) { 
      // if (Config.LOGD) Log.d(TAG, "request time failed: " + e); 
      return false; 
     } 

     return true; 
    } 


    public long getNtpTime() { 
     return mNtpTime; 
    } 


    /** 
     * Reads an unsigned 32 bit big endian number from the given offset in the buffer. 
     */ 
    private long read32(byte[] buffer, int offset) { 
     byte b0 = buffer[offset]; 
     byte b1 = buffer[offset+1]; 
     byte b2 = buffer[offset+2]; 
     byte b3 = buffer[offset+3]; 

     // convert signed bytes to unsigned values 
     int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0); 
     int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1); 
     int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2); 
     int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3); 

     return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3; 
    } 

    /** 
     * Reads the NTP time stamp at the given offset in the buffer and returns 
     * it as a system time (milliseconds since January 1, 1970). 
     */  
    private long readTimeStamp(byte[] buffer, int offset) { 
     long seconds = read32(buffer, offset); 
     long fraction = read32(buffer, offset + 4); 
     return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L)/0x100000000L);   
    } 

    /** 
     * Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900 
     */  
    private void writeTimeStamp(byte[] buffer, int offset) {   
     int ofs = offset++; 

     for (int i=ofs;i<(ofs+8);i++) 
      buffer[i] = (byte)(0);    
    } 

} 

String get_time_zone_time(GeoPoint gp){ 

     String erg = ""; 
     String raw_offset = ""; 
     String dst_offset = ""; 

     double Longitude = gp.getLongitudeE6()/1E6; 
     double Latitude = gp.getLatitudeE6()/1E6; 

     // String request = "http://ws.geonames.org/timezone?lat="+Latitude+"&lng="+ Longitude+ "&style=full"; 


     long tsLong = 0; // System.currentTimeMillis()/1000; 

     NTP_UTC_Time client = new NTP_UTC_Time(); 

     if (client.requestTime("pool.ntp.org", 2000)) {    
      tsLong = client.getNtpTime(); 
     } 

     if (tsLong != 0) 
     { 

     tsLong = tsLong/1000; 

     // https://maps.googleapis.com/maps/api/timezone/xml?location=39.6034810,-119.6822510&timestamp=1331161200&sensor=true 

     String request = "https://maps.googleapis.com/maps/api/timezone/xml?location="+Latitude+","+ Longitude+ "&timestamp="+tsLong +"&sensor=true"; 

     String xmltext = get_xml_server_reponse(request); 

     if(xmltext.compareTo("")!= 0) 
     { 

     int startpos = xmltext.indexOf("<TimeZoneResponse"); 
     xmltext = xmltext.substring(startpos); 



     XmlPullParser parser; 
     try { 
      parser = XmlPullParserFactory.newInstance().newPullParser(); 


      parser.setInput(new StringReader (xmltext)); 

      int eventType = parser.getEventType(); 

      String tagName = ""; 


      while(eventType != XmlPullParser.END_DOCUMENT) { 
       switch(eventType) { 

        case XmlPullParser.START_TAG: 

          tagName = parser.getName(); 

         break; 


        case XmlPullParser.TEXT : 


         if (tagName.equalsIgnoreCase("raw_offset")) 
          if(raw_offset.compareTo("")== 0)        
          raw_offset = parser.getText(); 

         if (tagName.equalsIgnoreCase("dst_offset")) 
          if(dst_offset.compareTo("")== 0) 
          dst_offset = parser.getText(); 


         break; 

       } 

       try { 
         eventType = parser.next(); 
        } catch (IOException e) { 

         e.printStackTrace(); 
        } 

       } 

       } catch (XmlPullParserException e) { 

        e.printStackTrace(); 
        erg += e.toString(); 
       } 

     }  

     int ro = 0; 
     if(raw_offset.compareTo("")!= 0) 
     { 
      float rof = str_to_float(raw_offset); 
      ro = (int)rof; 
     } 

     int dof = 0; 
     if(dst_offset.compareTo("")!= 0) 
     { 
      float doff = str_to_float(dst_offset); 
      dof = (int)doff; 
     } 

     tsLong = (tsLong + ro + dof) * 1000; 



     erg = get_UTC_Datetime_from_timestamp(tsLong); 
     } 


    return erg; 

} 

而且隨着使用它:

GeoPoint gp = new GeoPoint(39.6034810,-119.6822510); 
String Current_TimeZone_Time = get_time_zone_time(gp); 
+0

可能有些代碼從你的示例代碼couldn '找到方法'String get_xml_server_reponse(String request)'。你能否提供那個..? – 2016-05-15 10:39:20

+0

我無法完美地格式化請求字符串,並且您的答案對我有幫助。謝謝!! – 2016-05-15 14:16:29

1

另一種選擇是使用llttz庫,該庫Android設備的端口APTimeZones項目。用法很簡單:

IConverter iconv = Converter.getInstance(TimeZoneListStore.class); 
TimeZone tz = iconv.getTimeZone(53.5233333, 49.4125); 

庫很小,不需要Internet連接。缺點是計算有時不準確,這是由於我計算TimeZone的方式。關於這方面的更多信息可以在here找到。