将系统时间更改为提前三小时,然后再返回默认值

时间:2014-01-24 17:28:44

标签: java command-line

我一直在尝试将系统时间改为三小时,然后又回到默认状态,但我似乎没有得到我想要的时间。不是cal.setTimeZone(TimeZone.getTimeZone(“America / Los_Angeles”));假设将时间设置为America / Los_Angeles Timezone?

public static void changeSystemTime() throws Exception {

    DateFormat dateFormat = new SimpleDateFormat("HH:mm");

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));

    System.out.println("Current time is " + dateFormat.format(cal.getTime());

    cal.add(Calendar.HOUR_OF_DAY, 3);
    System.out.println("3 Hours from now is " + dateFormat.format(cal.getTime());

    Runtime runtime = Runtime.getRuntime();

    runtime.exec("cmd /c Time " + dateFormat.format(cal.getTime()));
}

public static void changeSystemTimeToDefault() throws Exception {

    DateFormat dateFormat = new SimpleDateFormat("HH:mm");

    Date date = new Date();

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));

    System.out.println("Timezone for LA is " + dateFormat.format(cal.getTime());

    Runtime runtime = Runtime.getRuntime();

    runtime.exec("cmd /c Time " + dateFormat.format(cal.getTime()));
}

2 个答案:

答案 0 :(得分:1)

你实际上在方法改变系统时间()中没有增加3个小时;

原因:

String time = dateFormat.format(cal.getTime());
System.out.println("Current time is " + time);

cal.add(Calendar.HOUR_OF_DAY, 3);
// here you again work with the initial time, the 3 hours are not added to it
System.out.println("3 Hours from now is " + time);

这样做:

cal.add(Calendar.HOUR_OF_DAY, 3);
// get new time
System.out.println("3 Hours from now is " + cal.getTime());

答案 1 :(得分:0)

您可以使用JNI设置系统时间。这适用于Windows。你需要知道JNI和C.

这是JNI函数,原型将由javah实用程序生成

JNIEXPORT void JNICALL Java_TimeSetter_setSystemTime   (JNIEnv * env,jobject obj,jshort hour,jshort分钟){

SYSTEMTIME st;
GetLocalTime(&st);  
st.wHour = hour;      
st.wMinute = minutes;  
SetLocalTime(&st);   

} Java JNI包装器将是

class TimeSetter {

public native void setSystemTime( short hour, short minutes);

static {
    System.loadLibrary("TimeSetter");
}

} 最后,使用它

公共类JNITimeSetter {

public static void main(String[] args) {

    short hour = 8;
    short minutes = 30;

    // Set the system at 8h 30m

    TimeSetter ts = new TimeSetter();
    ts.setSystemTime(hour, minutes);
}

}