Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current time from internet in android

Tags:

android

time

I am making an app in which I want to get the current time from internet.

I know how to get the time from the device using System.currentTimeMillis, and even after searching a lot, I did not get any clue about how to get it from internet.

like image 780
user1726619 Avatar asked Oct 25 '12 08:10

user1726619


People also ask

How can I get current time in Android?

text. DateFormat. getDateTimeInstance(). format(new Date()); // textView is the TextView view that should display it textView.

How do I get GMT on my Android?

text. SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); dfgmt. setTimeZone(TimeZone. getTimeZone("GMT")); String gmtTime = dfgmt.

How does Android store date and time?

Saving DateTime in Android String – you can simply save your datetime as String (Text in SQLite) if all you want to do with the date going forward is display it. Also you can use DateFormat to parse the saved String to date value and work with it later. Product temp = new Product(); temp.

How do I get the current date and time in Kotlin?

As Kotlin is interoperable with Java, we will be using the Java utility class and Simple Date Format class in order to get the current local date and time.


Video Answer


2 Answers

You can get time from internet time servers using the below program

import java.io.IOException;

import org.apache.commons.net.time.TimeTCPClient;

public final class GetTime {

    public static final void main(String[] args) {
        try {
            TimeTCPClient client = new TimeTCPClient();
            try {
                // Set timeout of 60 seconds
                client.setDefaultTimeout(60000);
                // Connecting to time server
                // Other time servers can be found at : http://tf.nist.gov/tf-cgi/servers.cgi#
                // Make sure that your program NEVER queries a server more frequently than once every 4 seconds
                client.connect("time.nist.gov");
                System.out.println(client.getDate());
            } finally {
                client.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1.You would need Apache Commons Net library for this to work. Download the library and add to your project build path.

(Or you can also use the trimmed Apache Commons Net Library here : https://www-us.apache.org/dist//commons/net/binaries/commons-net-3.6-bin.tar.gz This is enough to get time from internet )

2.Run the program. You will get the time printed on your console.

like image 102
sunil Avatar answered Oct 28 '22 05:10

sunil


Here is a method that i have created for you you can use this in your code

public String getTime() {
try{
    //Make the Http connection so we can retrieve the time
    HttpClient httpclient = new DefaultHttpClient();
    // I am using yahoos api to get the time
    HttpResponse response = httpclient.execute(new
    HttpGet("http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo"));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        // The response is an xml file and i have stored it in a string
        String responseString = out.toString();
        Log.d("Response", responseString);
        //We have to parse the xml file using any parser, but since i have to 
        //take just one value i have deviced a shortcut to retrieve it
        int x = responseString.indexOf("<Timestamp>");
        int y = responseString.indexOf("</Timestamp>");
        //I am using the x + "<Timestamp>" because x alone gives only the start value
        Log.d("Response", responseString.substring(x + "<Timestamp>".length(),y) );
        String timestamp =  responseString.substring(x + "<Timestamp>".length(),y);
        // The time returned is in UNIX format so i need to multiply it by 1000 to use it
        Date d = new Date(Long.parseLong(timestamp) * 1000);
        Log.d("Response", d.toString() );
        return d.toString() ;
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }
}catch (ClientProtocolException e) {
Log.d("Response", e.getMessage());
}catch (IOException e) {
Log.d("Response", e.getMessage());
}
return null;
}
like image 8
Girish Nair Avatar answered Oct 28 '22 04:10

Girish Nair