http://hi.baidu.com/captives/item/25c8b80170a9b0ccf45ba6f8

————————————————————————————————————————————————————————

    package dtm.tools;  

      

    import java.io.BufferedInputStream;  

    import java.io.BufferedReader;  

    import java.io.IOException;  

    import java.io.InputStream;  

    import java.io.InputStreamReader;  

    import java.net.Socket;  

    import java.net.UnknownHostException;  

    import java.util.Calendar;  

    import java.util.Date;  

    import java.util.TimeZone;  

    import java.util.logging.Level;  

    import java.util.logging.Logger;  

      

    /** 

     * SyncTime 获取原子钟的时间,并设置为系统时间 

     * @author Administrator 

     */  

    public class SyncTime {  

      

        private static int sleepMinutes = 0;  

        private static final long EPOCH_OFFSET_MILLIS;  

        private static final String[] hostName = {"time-a.nist.gov", "time-nw.nist.gov", "time.nist.gov"};  

      

      

        static {  

            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));  

            // Java使用的参照标准是1970年,而时间服务器返回的秒是相当1900年的,算一下偏移   

            calendar.set(1900, Calendar.JANUARY, 1, 0, 0, 0);  

            EPOCH_OFFSET_MILLIS = Math.abs(calendar.getTime().getTime());  

        }  

      

        public static void main(String[] args) {  

            GetWebTime();  

        }  

      

        private static Date getNetDate(String hostName) {  

            Date date = null;  

            long result = 0;  

            try {  

                Socket socket = new Socket(hostName, 37);  

                BufferedInputStream bis = new BufferedInputStream(socket.getInputStream(),  

                        socket.getReceiveBufferSize());  

                int b1 = bis.read();  

                int b2 = bis.read();  

                int b3 = bis.read();  

                int b4 = bis.read();  

                if ((b1 | b2 | b3 | b3) < 0) {  

                    return null;  

                }  

                result = (((long) b1) << 24) + (b2 << 16) + (b3 << 8) + b4;  

                date = new Date(result * 1000 - EPOCH_OFFSET_MILLIS);  

                socket.close();  

            } catch (UnknownHostException ex) {  

                Logger.getLogger(SyncTime.class.getName()).log(Level.SEVERE, null, ex);  

            } catch (IOException ex) {  

                Logger.getLogger(SyncTime.class.getName()).log(Level.SEVERE, null, ex);  

            }  

            return date;  

        }  

      

        /** 

         * 通过ping命令判断是否离线 

         * @return 

         */  

        public static boolean offLine() {  

            Runtime run = Runtime.getRuntime();  

            try {  

                Process process = run.exec("ping www.hao123.com");  

                InputStream s = process.getInputStream();  

                BufferedReader bis = new BufferedReader(new InputStreamReader(s));  

                String str = bis.readLine();  

                while (str != null) {  

                    if (str.startsWith("Reply from")) {  

                        return false;  

                    }  

                    str = bis.readLine();  

                }  

                process.waitFor();  

            } catch (IOException ex) {  

                Logger.getLogger(SyncTime.class.getName()).log(Level.SEVERE, null, ex);  

            } catch (InterruptedException ex) {  

                Logger.getLogger(SyncTime.class.getName()).log(Level.SEVERE, null, ex);  

            }  

            return true;  

        }  

      

        /** 

         * 通过调用本地命令date和time修改计算机时间 

         * @param date 

         */  

        private static void setComputeDate(Date date) {  

            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));  

            c.setTime(date);  

            int year = c.get(Calendar.YEAR);  

            int month = c.get(Calendar.MONTH) + 1;  

            int day = c.get(Calendar.DAY_OF_MONTH);  

            int hour = c.get(Calendar.HOUR_OF_DAY);  

            int minute = c.get(Calendar.MINUTE);  

            int second = c.get(Calendar.SECOND);  

      

            c.setTime(new Date());  

            int year_c = c.get(Calendar.YEAR);  

            int month_c = c.get(Calendar.MONTH) + 1;  

            int day_c = c.get(Calendar.DAY_OF_MONTH);  

            int hour_c = c.get(Calendar.HOUR_OF_DAY);  

            int minute_c = c.get(Calendar.MINUTE);  

      

            String ymd = year + "-" + month + "-" + day;  

            String time = hour + ":" + minute + ":" + second;  

            try {  

                // 日期不一致就修改一下日期   

                if (year != year_c || month != month_c || day != day_c) {  

                    String cmd = "cmd /c date " + ymd;  

                    Process process = Runtime.getRuntime().exec(cmd);  

                    process.waitFor();  

                }  

      

                // 时间不一致就修改一下时间   

                if (hour != hour_c || minute != minute_c) {  

                    String cmd = "cmd  /c  time " + time;  

                    Process process = Runtime.getRuntime().exec(cmd);  

                    process.waitFor();  

                }  

            } catch (IOException ex) {  

                Logger.getLogger(SyncTime.class.getName()).log(Level.SEVERE, null, ex);  

            } catch (InterruptedException ex) {  

                Logger.getLogger(SyncTime.class.getName()).log(Level.SEVERE, null, ex);  

            }  

        }  

          

        public static void GetWebTime()  

        {  

            // 检测电脑是否在线   

            while (offLine() && sleepMinutes < 30) {  

                try {  

                    Thread.sleep(120000);  

                    sleepMinutes += 2;  

                } catch (InterruptedException ex) {  

                    Logger.getLogger(SyncTime.class.getName()).log(Level.SEVERE, null, ex);  

                }  

            }  

      

            // 30分钟还没有联线,表示就不上网了,退出吧   

            if (sleepMinutes >= 30)  

            {  

                System.exit(0);  

            }  

      

            // 从网络上获取时间   

            Date date = null;  

            for (int i = 0; i < hostName.length; i++) {  

                date = getNetDate(hostName[i]);  

                if (date != null) {  

                    break;  

                }  

            }  

      

            // 修改本机时间   

            if (date != null) {  

                System.out.println("原子钟时间:"+date);  

                setComputeDate(date);  

            }  

        }  

    } 

java 获取服务器时间同步本地计算机时间的更多相关文章

  1. java获取服务器路径

    java获取服务器一些信息的方法(服务器地址/相对路径/端口/项目名字 request.getServletContext().getRealPath("/")  获取项目所在服务 ...

  2. java获取本月开始时间和结束时间、上个月第一天和最后一天的时间以及当前日期往前推一周、一个月

    import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.uti ...

  3. Java获取当前的日期和时间

    Java获取当前的日期和时间 1.具体实现方法如下 /** * @Title:DateTime.java * @Package:com.you.model * @Description:获取当前的日期 ...

  4. java获取服务器IP地址及MAC地址的方法

    这篇文章主要介绍了java编程实现获取机器IP地址及MAC地址的方法,实例分析了Java分别针对单网卡及多网卡的情况下获取服务器IP地址与MAC地址的相关技巧,需要的朋友可以参考下   本文实例讲述了 ...

  5. java获取服务器基本信息

    实现步骤: (1)创建servlet BrowserServer (2)调用HttpServletRequest对象的getServerName()方法获取服务器名称 (3)调用HttpServlet ...

  6. java获取服务器的ip和地址

    HttpServletRequest httpRequest=(HttpServletRequest)request; String strBackUrl = "http://" ...

  7. java获取服务器一些信息的方法

    request.getServletContext().getRealPath("/") 获取项目所在服务器的全路径,如:D:\Program Files\apache-tomca ...

  8. java 获取的是本地的IP地址

    1 public static void main(String[] args) { 2 try { 3 InetAddress address = InetAddress.getLocalHost( ...

  9. JAVA获取服务器路径的方法

    1.在JSF环境中获取到ServletContext: 1 2 ServletContext sc = (ServletContext)FacesContext.         getCurrent ...

随机推荐

  1. 转:关于腾讯bugly崩溃的android so符号表使用

    http://www.jikexueyuan.com/course/406_8.html

  2. Android轻量级的开源缓存框架ASimpleCache

    点击查看原文 先上方法调用,写最经常使用的.其它不一一写 保存数据: ACache mACache=ACache.get(this); mACache.put("数据名称", js ...

  3. minic 符号表

    #include <stdio.h> #include <string.h> #include <malloc.h> typedef struct _array_d ...

  4. 有关﹤![CDATA[ ]]> 说明

    CDATA DTD中的属性类型 全名:character data 在标记CDATA下,所有的标记.实体引用都被忽略,而被XML处理程序一视同仁地当做字符数据看待, CDATA的形式如下: <! ...

  5. PortableApps的使用方法

    1 从官方网站下载这个软件,建议只下载PortableApps Platform Only即可,因为官方提供的软件其实很少,大多数需要我们自己添加. PortableApps 致力于将一些常见的开源软 ...

  6. C# 5 in a Nutshell - Delegate

    1. What is delegate in C#? A delegate is an object that knows how to call a method.A delegate type d ...

  7. win 2003 / IIS6 部署网站的时候,文件IO操作、删除项目文件, 会导致IIS重启,Session丢失问题

    项目中经常需要打些日志(文件IO读写操作),已记录调试.错误等信息.比较方便的有log4net等开源项目. 问题描述: 最近用win 2003 / IIS6,部署了一个2.0 的网站,在操作文件的时候 ...

  8. 【MVC5】使用域用户登录+记住我

    1.配置Web.config文件 添加域链接字符串 <connectionStrings> <add name="ADConnectionString" conn ...

  9. gensim自然语言处理(续)

    上一篇,已经实现了如何将一条语句在一个语料库中比较相似度, 发现运行的时候每次都要编译语料库,通过查找资料,可以一次性编译成预料库,存人文件 编译语料库代码 11_k.py import sysimp ...

  10. Linux配置虚拟主机后,只能访问到主页怎么办?

    Linux配置虚拟主机后,只能访问到主页怎么办? 今天配置了lamp后,添加了一个虚拟主机,配置http.conf后,增加虚拟主机,测试访问发现只有域名下能访问,ljt.com但是域名下所有的都访问不 ...