How to get a time zone from a location using latitude and longitude coordinates?

后端 未结 17 1561
走了就别回头了
走了就别回头了 2020-11-21 04:38

Given the latitude and longitude of a location, how does one know what time zone is in effect in that location?

In most cases, we are looking for an IANA/Olson time z

17条回答
  •  独厮守ぢ
    2020-11-21 05:11

    by using latitude and longitude get time zone of current location below code worked for me

    String data = null;         
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Location ll = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    double lat = 0,lng = 0;
    if(ll!=null){
        lat=ll.getLatitude();
        lng=ll.getLongitude();
    }
    System.out.println(" Last known location of device  == "+lat+"    "+lng);
    
    InputStream iStream = null; 
    HttpURLConnection urlConnection = null;
    try{
        timezoneurl = timezoneurl+"location=22.7260783,75.8781553×tamp=1331161200";                    
        // timezoneurl = timezoneurl+"location="+lat+","+lng+"×tamp=1331161200";
    
        URL url = new URL(timezoneurl);                
        // Creating an http connection to communicate with url 
        urlConnection = (HttpURLConnection) url.openConnection(); 
    
        // Connecting to url 
        urlConnection.connect();                
    
        // Reading data from url 
        iStream = urlConnection.getInputStream();
    
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
    
        StringBuffer sb  = new StringBuffer();
        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    
    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        try {
            iStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        urlConnection.disconnect();
    }
    
    try {
        if(data!=null){
            JSONObject jobj=new JSONObject(data);
            timezoneId = jobj.getString("timeZoneId");
    
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            format.setTimeZone(TimeZone.getTimeZone(timezoneId));
    
            Calendar cl = Calendar.getInstance(TimeZone.getTimeZone(timezoneId));
            System.out.println("time zone id in android ==  "+timezoneId);
    
            System.out.println("time zone of  device in android == "+TimeZone.getTimeZone(timezoneId));
            System.out.println("time fo device in android "+cl.getTime());
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

提交回复
热议问题