Search code examples
javaandroidtimeutcntp

How do I get the current time from the internet?


I have browsed the whole site to find a solution. But none of the ones I found worked. And most of them were pretty old. So I want to get the current UTC time from the internet. Completely independent from the phone.

Would be nice if someone could help me.


Solution

  • This is a free time service which returns the number of minutes since the Unix epoch: https://currentmillis.com/time/minutes-since-unix-epoch.php

    The Unix epoch is 00:00:00 UTC Thursday, 1 January 1970

    Here is some code to fetch this number and create an Instant object out of it in Java:

    URL url = new URL("https://currentmillis.com/time/minutes-since-unix-epoch.php");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    long minutes = Long.parseLong(in.readLine());
    in.close();
    con.disconnect();
    Instant instant = Instant.ofEpochSecond(minutes * 60);
    

    Note that the time resolution of this service is in minutes, so it will not be accurate to the second, you have to decide whether it's sufficient to your purposes. Also note that if you ship this code it would be nice to make it more robust (e.g. proper exception handling). If there's need for more precise times, NTP is the way: use of ntp service