java
修改系统时间方法
第一种方法:
需下载
jna.jar
a)
创建
Kernel32
接口
package
time.test;
import
com.sun.jna.Native;
import
com.sun.jna.Structure;
import
com.sun.jna.win32.StdCallLibrary;
public
interface
Kernel32
extends
StdCallLibrary
{
Kernel32 INSTANCE
=
(Kernel32)Native.loadLibrary(
"
kernel32
"
, Kernel32.
class
);
public
SYSTEMTIME GetSystemTime();
public
void
SetLocalTime(SYSTEMTIME localTime);
public
static
class
SYSTEMTIME
extends
Structure
{
//
必须有这么多个字段,按这个顺序定义属性
public
short
wYear;
public
short
wMonth;
public short wDayOfWeek;
public
short
wDay;
public
short
wHour;
public
short
wMinute;
public
short
wSecond;
public
short
wMilliseconds;
}
}
b)
修改时间
import
time.test.Kernel32.SYSTEMTIME;
public
class
SysTimeSettingDaoImp
{
protected
void
setLocalTime(String time)
{
//
time时间格式是14位的字符串,如"20080108152130"
Short year
=
Short.parseShort(time.substring(
0
,
4
));
Short month
=
Short.parseShort(time.substring(
4
,
6
));
Short day
=
Short.parseShort(time.substring(
6
,
8
));
Short hour
=
Short.parseShort(time.substring(
8
,
10
));
Short minute
=
Short.parseShort(time.substring(
10
,
12
));
Short second
=
Short.parseShort(time.substring(
12
,
14
));
SYSTEMTIME ss
=
new
SYSTEMTIME();
ss.setWYear(year);
ss.setWMonth(month);
ss.setWDay(day);
ss.setWHour(hour);
ss.setWMinute(minute);
ss.setWSecond(second);
Kernel32 lib
=
Kernel32.INSTANCE;
lib.SetLocalTime(ss);
}
}
第二种方法
public
class
MyTimeClass
{
//
timeAndDate格式位14位的字符串表示形式。
public
void
setLocalTime(String timeAndDate)
{
String date
=
getDate(timeAndDate);
String time
=
getTime(timeAndDate);
//
修改系统日期和时间
Runtime.getRuntime().exec(
"
cmd /c date
"
+
date);
Runtime.getRuntime().exec(
"
cmd /c time
"
+
time);
}
public
String getDate(String timeAndDate)
{
String year
=
timeAndDate.substring(
0
,
4
);
String month
=
timeAndDate.substring(
4
,
6
);
String day
=
timeAndDate.substring(
6
,
8
);
return
year
+
"
-
"
+
month
+
"
-
"
+
day;
}
public
String getTime(String timeAndDate)
{
String hour
=
timeAndDate.substring(
8
,
10
);
String minute
=
timeAndDate.substring(
10
,
12
);
String second
=
timeAndDate.substring(
12
,
14
);
return
hour
+
"
:
"
+
minute
+
"
:
"
+
second;
}
}
Linux系统修改时间