Search code examples
javatimeapache-commonsapache-commons-net

Determine the internet time of another country in Java


I am developing a Java application that will be used by people from around the world. One feature requires it to display the current time in Melbourne, Australia.

I have found this answer and adapted the code as follows, but it returns my current time (as expected). It uses the Apache Commons Net library:

    try {
        String TIME_SERVER = "time-a.nist.gov";   
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
        return new Date(returnTime);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return null;
    }

How can I modify this code to return the time in Melbourne, rather than my time? I am open to other solutions to solve this problem as well.

Thank you!

EDIT:

Taking Jon's advice, I have used the JodaTime library and built the following code to solve the problem. It can be used for other time zones by changing Australia/Melbourne to any timezone found here.

    try {
        //Get the time for the current time zone.
        String TIME_SERVER = "time-a.nist.gov";   
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();

        //Format it to the Melbourne TimeZone.
        DateTimeZone tzMelbourne = DateTimeZone.forID("Australia/Melbourne");
        return new DateTime(returnTime).toDateTime(tzMelbourne);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return null;
    }

Solution

  • You're currently returning a java.util.Date - that doesn't have a time zone. It's just an instant in time. It's not in your time zone, or some other time zone - it's just an instant. When you call toString(), that will give you a textual representation in your local time zone, but that's not part of the data in the object.

    If you need to represent "a date/time in a particular time zone" then you should use the Calendar class, or ideally use Joda Time which is a much better date/time API.

    Alternatively, if you're just trying to format the date/time in a particular time zone, you can use SimpleDateFormat - set the time zone, and then format the Date value you're already returning.