3 import java.io.IOException;
4 import java.net.InetAddress;
6 import java.util.Objects;
8 import org.apache.commons.net.ntp.NTPUDPClient;
9 import org.apache.commons.net.ntp.NtpV3Packet;
10 import org.apache.commons.net.ntp.TimeInfo;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
15 * JST(日本標準時)を <a href="https://www.nict.go.jp/">情報通信研究機構</a> から取得するユーティリティクラスです
24 private static final Logger LOG = LoggerFactory.getLogger(JST.class);
25 private static final String SERVER_NAME = "ntp.nict.jp";
27 // private constructor
28 private JST() { /* do nothing */ }
31 * フィールド {@link #SERVER_NAME} で指定されているサーバーから時刻を取得し、そのまま {@link Date} 型に変換して返却します。
34 * @throws IOException 日本標準時取得時に入出力エラーが起こった場合
36 public static Date JSTNow() throws IOException {
37 NTPUDPClient client = new NTPUDPClient();
38 InetAddress address = InetAddress.getByName(SERVER_NAME);
40 TimeInfo info = client.getTime(Objects.requireNonNull(address));
41 info.computeDetails();
42 LOG.debug("NTPClient: {}", client);
43 LOG.debug("NetAddress: {}", address);
44 LOG.debug("Time info: {}", info);
45 return validate(info);
49 * 渡された引数から独自にオフセットを計算し、取得した情報との加重平均を取って返します。
51 * 基本は取得オフセットと同じ値になることが予想されます。
52 * @param info サーバーから取得した情報
53 * @param packet サーバーから取得した情報のパケット
56 private static Date validate(TimeInfo info) {
57 final NtpV3Packet packet = info.getMessage();
58 long t1 = packet.getOriginateTimeStamp().getTime();
59 long t2 = packet.getReceiveTimeStamp().getTime();
60 long t3 = packet.getTransmitTimeStamp().getTime();
61 long t4 = info.getReturnTime();
62 long CalculatedOffset = (t2 - t1 + t3 - t4) / 2;
63 long receiveOffset = info.getOffset();
64 long offset = ( CalculatedOffset + receiveOffset ) / 2;
65 Date date = new Date(System.currentTimeMillis() + offset);
66 LOG.debug("Client originate Time: {}", t1);
67 LOG.debug("Server Received request Time: {}", t2);
68 LOG.debug("Server Transmit response Time: {}", t3);
69 LOG.debug("Client Received response Time: {}", t4);
70 LOG.info("Estimated time offset: {}", CalculatedOffset);
71 LOG.info("received time offset: {}", receiveOffset);
72 LOG.info("estimated JST: {}", date);
73 LOG.info("Current client date: {}", new Date(System.currentTimeMillis()));