3

I want to know if there is any API/class in android which can give us the original date as I do not want to get the date/time from android device.

Puneetr90
  • 199
  • 1
  • 6
  • 18

4 Answers4

7

Updated!!

The old answer does not work because the timeapi.org is down.

Here is the my new getTime method. It's using JSOUP.

private long getTime() throws Exception {
    String url = "https://time.is/Unix_time_now";
    Document doc = Jsoup.parse(new URL(url).openStream(), "UTF-8", url);
    String[] tags = new String[] {
            "div[id=time_section]",
            "div[id=clock0_bg]"
    };
    Elements elements= doc.select(tags[0]);
    for (int i = 0; i <tags.length; i++) {
        elements = elements.select(tags[i]);
    }
    return Long.parseLong(elements.text());
}

To convert timestamp into readable date and time

private String getDate(long time) {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time * 1000);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm a", Locale.ENGLISH);
    
    return dateFormat.format(cal.getTime());
} 

Gradle:

implementation 'org.jsoup:jsoup:1.10.2'
Marsad
  • 859
  • 1
  • 14
  • 35
Mete
  • 2,805
  • 1
  • 28
  • 38
0

Use This

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;
}
Quick learner
  • 10,632
  • 4
  • 45
  • 55
0

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("nist.time.nosc.us");
                    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.dropbox.com/s/bjxjv7phkb8xfhh/commons-net-3.1.jar. This is enough to get time from internet )

Santosh Shinde
  • 6,045
  • 7
  • 44
  • 68
-1

You can use the android.net.sntp.SntpClient class.

SntpClient client = new SntpClient();
int timeout = 50000;
if (client.requestTime("time-a.nist.gov", timeout)) {
    long time = client.getNtpTime();
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(time);
    calendar.getTime();  // this should be your date
}
GVillani82
  • 17,196
  • 30
  • 105
  • 172