admin 管理员组

文章数量: 1184232

虚拟机系统的时间总是不对,每次都要修改时间,很麻烦,所以写了个简单的同步时间的代码,windows有效,linux可以自己查命令,修改命令即可:

系统环境:

系统: Windows32

JDK版本:jdk1.6.45

开发工具:eclipse

package com.siqi;

import java.io.IOException;
import java.MalformedURLException;
import java.URL;
import java.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class OSTime {

    public static void main(String[] args) throws MalformedURLException, IOException, ParseException,
            InterruptedException {

        System.out.println("开始访问百度服务器:http://www.baidu");
        URLConnection conn = new URL("http://www.baidu").openConnection();
        String dateStr = conn.getHeaderField("Date");
        System.out.println("获取到的服务器时间:" + dateStr);

        // 解析为北京时间:GMT+8
        DateFormat httpDateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.US);
        httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        Date date = httpDateFormat.parse(dateStr);
        System.out.println("解析成北京时间格式:" + date);

        // 解析成简洁的日期格式
        DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        dateTimeFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        System.out.println("解析成标准时间格式:" + dateTimeFormat.format(date));

        // 取日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        dateTimeFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String currDate = dateFormat.format(date);

        // 设置Windows系统日期
        Process exec = Runtime.getRuntime().exec("cmd /c date " + currDate);
        if (exec.waitFor() == 0) {
            System.out.println("设置系统日期成功:" + currDate);
        } else {
            System.out.println("设置系统日期失败:" + currDate);
        }

        // 取时间
        DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.US);
        timeFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String currTime = timeFormat.format(date);

        // 设置Windows系统时间
        exec = Runtime.getRuntime().exec("cmd /c time " + currTime);
        if (exec.waitFor() == 0) {
            System.out.println("设置系统时间成功:" + currTime);
        } else {
            System.out.println("设置系统时间失败:" + currTime);
        }

    }
}

执行结果:

开始访问百度服务器:http://www.baidu
获取到的服务器时间:Fri, 23 Aug 2013 15:14:03 GMT
解析成北京时间格式:Fri Aug 23 23:14:03 CST 2013
解析成标准时间格式:2013-08-23 23:14:03
设置系统日期成功:2013-08-23
设置系统时间成功:23:14:03

可以把这段代码到处成一个可执行的Jar包

步骤:

1.工程结构如下

.

2.右键,选择Export(导出)


3.导出成一个可执行的Jar文件  Java->Runnable JAR file



4. Launch configuration,执行的主入口,要选对哈,Export destination要保存的文件内容。点击Finish即可



5.可以看到可执行包,双击即可修改同步系统时间,标准时间取的是百度服务器时间,应该挺准的吧。。。



本文标签: 时间 系统 java Windows