Home >Java >javaTutorial >How Can I Retrieve Greenwich Mean Time (GMT) from Internet Time Servers in Java?
Retrieving Time from Internet Time Servers in Java
This discussion centers around obtaining Greenwich Mean Time (GMT) from an external source rather than relying on the local system. Time synchronization servers offer a solution to this need.
Java-Based Approach
To retrieve time from a time server in Java, consider the following approach:
Using the JNTP Library (or a Similar One)
External libraries exist to facilitate this task. JNTP, for example, provides a straightforward interface for accessing time servers.
Establishing a Connection to the Time Server
Once you have selected a library, establish a connection to the desired time server using that library's methods. The code below demonstrates this using the JNTP library:
import org.jnbt.NTPUDPClient; import org.jnbt.TimeInfo; import java.net.InetAddress; String TIME_SERVER = "time-a.nist.gov"; NTPUDPClient timeClient = new NTPUDPClient(); InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
Retrieving the Time
Depending on the library you are using, the method for retrieving the time may vary. With JNTP, you can obtain the server's time like this:
TimeInfo timeInfo = timeClient.getTime(inetAddress); long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime(); Date time = new Date(returnTime);
Remember that using timeInfo.getReturnTime() will return the current system time, not the received time. Instead, use timeInfo.getMessage().getTransmitTimeStamp().getTime().
The above is the detailed content of How Can I Retrieve Greenwich Mean Time (GMT) from Internet Time Servers in Java?. For more information, please follow other related articles on the PHP Chinese website!