how to make my java app get global time from some online clock

前端 未结 5 1735
温柔的废话
温柔的废话 2020-12-07 02:51

I am making a distributed java app for which I need both parts of the app to run on one standard time. Since system times can be different I was thinking if java API contain

5条回答
  •  一向
    一向 (楼主)
    2020-12-07 03:19

    Thanks Rajendra_Prasad that's true

    public static void main(String[] args) throws Exception {
            NTPUDPClient timeClient = new NTPUDPClient();
            InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
            TimeInfo timeInfo = timeClient.getTime(inetAddress);
            long returnTime = timeInfo.getReturnTime();
            Date time = new Date(returnTime);
            long systemtime = System.currentTimeMillis();
            timeInfo.computeDetails();
            Date realdate = new Date(systemtime + timeInfo.getOffset());
            System.out.println("Time from " + TIME_SERVER + ": " + time);
            System.out.println("Time from " + TIME_SERVER + ": " + realdate);
            System.out.println(""+time.getTime());
        }
    

提交回复
热议问题