//
public static String getDatetime()
{
String dataTime = "";
String osName = System.getProperty("os.name");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss:SS");
if (osName.matches("^(?i)Windows.*$")) { // Window 系统
dataTime = df.format(System.currentTimeMillis());
} else if (osName.matches("^(?i)Linux.*$")) {// Linux 系统
dataTime = df.format(new Date()); // new Date()为获取当前系统时间
System.out.println("getDatetime="+dataTime);
} else {
//TODO
}
return dataTime;
}
public static void setDatetime(String dateTime) {
String osName = System.getProperty("os.name");
try {
if (osName.matches("^(?i)Windows.*$")) { // Window 系统
String cmd;
cmd = " cmd /c date " + date; // 格式:yyyy-MM-dd
Runtime.getRuntime().exec(cmd);
cmd = " cmd /c time " + time; // 格式 HH:mm:ss
Runtime.getRuntime().exec(cmd);
} else if (osName.matches("^(?i)Linux.*$")) {// Linux 系统
String command = "date -s " + dateTime;//2018.12.5-09:47:13";格式:yyyy-MM-dd-HH:mm:ss
System.out.println("----------------------setTime="+command);
Runtime.getRuntime().exec(command);
command = "hwclock -w";
Runtime.getRuntime().exec(command);
System.out.println("----------------------setTime="+command);
} else {
}
} catch (IOException e) {
//TODO
}
}
1、根据实验结果表明,Linux下date -s 后面的日期和时间千万别加引号,否则设置时间失败
2、获取的时间别用system.currentTimeMillis,再转成date格式。