あとで検索用
import java.net.InetAddress; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Optional; import org.apache.commons.net.ntp.NTPUDPClient; import org.apache.commons.net.ntp.TimeInfo; /** * NTPから現在日時を取得(日本専用) * @param arg NTPサーバ名。nullだと"ntp.nict.jp"を使う * @return 現在の日時 * @throws Exception */ public static LocalDateTime getLocalDateTimeFromNTP(String arg) throws Exception { Optional<String> ntpname=Optional.ofNullable(arg); NTPUDPClient ntpClient = new NTPUDPClient(); ntpClient.open(); TimeInfo timeInfo = ntpClient.getTime(InetAddress.getByName(ntpname.orElse( "ntp.nict.jp" ))); ntpClient.close(); // ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now()); このソフトの動作しているシステムの時差。海外鯖だとまずい事になりそう。 ZoneOffset offset = ZoneOffset.of("+09:00"); // 東京の時差 LocalDateTime ret = LocalDateTime.ofEpochSecond(timeInfo.getReturnTime()/1000,0, offset); // NTPから返るEPOCHはミリ秒なので1000で割る return ret; }
コメント