Reputation: 117
I´m trying to get the real current in my country, however the methods I used are dependant on the time on my device. I set the time on my device to 9 AM while in reality it was 7 PM and the following method returned 8 AM, which is ofcourse incorrect.
simpledate.setTimeZone(TimeZone.getTimeZone("Europe/Slovakia"));
to_time = simpledate.format(new Date());
Is there any way to get the real time in the country without it being dependant on system time? I assume the device must be connected to the Internet. Also my country uses DST, so it must take that into consideration too. Browsed similar question, none helped.
Upvotes: 0
Views: 494
Reputation: 190
package com.myapp.utils;
import android.os.StrictMode;
import java.io.IOException;
import org.apache.commons.net.time.TimeTCPClient;
public class InternetTime {
public static long getFechaHora() {
long time = 0;
try {
TimeTCPClient client = new TimeTCPClient();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
client.setDefaultTimeout(5000);
client.connect("time.nist.gov");
//System.out.println(client.getDate());
time = client.getTime();
} finally {
client.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
return time;
}
}
To avoid the networkonmainthreadexception
Upvotes: 0
Reputation: 1696
There are two ways to do that whether you will need to have access to a webservice that provides current date and time in JSON format or XML, OR, you could parse the time from a website, like
Another alternative code snippet for getting time from a Time Server. You need an Apache Commons Net libray for this to work.
import org.apache.commons.net.time.TimeTCPClient;
public final class GetTime {
public static final void main(String[] args) {
try {
TimeTCPClient client = new TimeTCPClient();
try {
client.setDefaultTimeout(60000);
client.connect("time.nist.gov");
System.out.println(client.getDate());
}
catch (IOException e) {
e.printStackTrace();
}
finally {
client.disconnect();
}
}
}
You can find other time servers at HERE. Just replace time.nist.gov
with one.
Upvotes: 1