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;
}