可以在Java中更改系统时间吗?
它应该可以在Windows和Linux下运行。我已经用中的Runtime
类尝试过了,但是权限有问题。
这是我的代码:
String cmd="date -s \""+datetime.format(ntp_obj.getDest_Time())+"\"";
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(cmd);
cmd
的输出为:
date -s "06/01/2011 17:59:01"
但是系统时间和以前一样。
我将设置时间,因为我正在编写一个NTP-Client,在那里我从NTP-Server获取时间并将其设置。
发布于 2011-06-01 23:41:55
您只能通过以root或管理员身份运行命令行工具来设置系统时间。命令有所不同,但您可以先检查操作系统,然后针对该操作系统运行相应的命令。
发布于 2013-06-11 10:40:31
您可以使用JNI
来设置系统时间。这在Windows上是可行的。你需要知道JNI
和C
。
这是JNI函数,原型将由javah
实用程序生成
JNIEXPORT void JNICALL Java_TimeSetter_setSystemTime
(JNIEnv *env, jobject obj, jshort hour, jshort minutes) {
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");
}
}
最后,为了使用它
public class 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);
}
}
发布于 2015-08-07 15:15:39
在某些情况下,进程不使用管理员权限运行,但仍具有设置系统时间的权限。可以使用Java Native Access更改系统时间,并拥有所有所需的Java源代码(与JNI相比更简单)。
package github.jna;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinBase.SYSTEMTIME;
import com.sun.jna.win32.StdCallLibrary;
/**
* Provides access to the Windows SetSystemTime native API call.
* This class is based on examples found in
* <a href="https://github.com/twall/jna/blob/master/www/GettingStarted.md">JNA Getting Started</a>
*/
public class WindowsSetSystemTime {
/**
* Kernel32 DLL Interface.
* kernel32.dll uses the __stdcall calling convention (check the function
* declaration for "WINAPI" or "PASCAL"), so extend StdCallLibrary
* Most C libraries will just extend com.sun.jna.Library,
*/
public interface Kernel32 extends StdCallLibrary {
boolean SetLocalTime(SYSTEMTIME st);
Kernel32 instance = (Kernel32) Native.loadLibrary("kernel32.dll", Kernel32.class);
}
public boolean SetLocalTime(SYSTEMTIME st) {
return Kernel32.instance.SetLocalTime(st);
}
public boolean SetLocalTime(short wYear, short wMonth, short wDay, short wHour, short wMinute, short wSecond) {
SYSTEMTIME st = new SYSTEMTIME();
st.wYear = wYear;
st.wMonth = wMonth;
st.wDay = wDay;
st.wHour = wHour;
st.wMinute = wMinute;
st.wSecond = wSecond;
return SetLocalTime(st);
}
}
https://stackoverflow.com/questions/6203857
复制相似问题