C++ 在c+内设置系统日期和时间+;linux程序
在我的程序中,用户以extjs形式选择日期和时间,然后数据将被发送到服务器端(c++程序)。在服务器程序中,日期和时间将应用于系统,如下所示:C++ 在c+内设置系统日期和时间+;linux程序,c++,linux,date,time,C++,Linux,Date,Time,在我的程序中,用户以extjs形式选择日期和时间,然后数据将被发送到服务器端(c++程序)。在服务器程序中,日期和时间将应用于系统,如下所示: int main(){ string date = "2013-08-28T00:00:00"; string newtime = "09:12"; time_t mytime = time(0); struct tm* tm_ptr = localtime(&mytime); if (tm_pt
int main(){
string date = "2013-08-28T00:00:00";
string newtime = "09:12";
time_t mytime = time(0);
struct tm* tm_ptr = localtime(&mytime);
if (tm_ptr)
{
tm_ptr->tm_mon = atoi(date.substr(5,2).c_str()) - 1;
tm_ptr->tm_mday = atoi(date.substr(8,2).c_str());
tm_ptr->tm_year = atoi(date.substr(0,4).c_str());
tm_ptr->tm_min = atoi(newtime.substr(3,2).c_str());
tm_ptr->tm_hour = atoi(newtime.substr(0,2).c_str());
printf("%d\n%d\n%d\n%d\n%d\n", tm_ptr->tm_mon,tm_ptr->tm_mday,tm_ptr->tm_year,tm_ptr->tm_min,tm_ptr->tm_hour);
const struct timeval tv = {mktime(tm_ptr), 0};
settimeofday(&tv, 0);
}
return 0;
}
但当运行此代码时,系统崩溃!
我还有另一个申请日期和时间的代码:
int main(){
string date = "2013-08-28T00:00:00";
string newtime = "09:12";
string newdate = "";
string monthnum = date.substr(5,2);
string month = "";
if(strcmp(monthnum.c_str(),"01") == 0) month = "Jan";
else if(strcmp(monthnum.c_str(),"02") == 0) month = "Feb";
else if(strcmp(monthnum.c_str(),"03") == 0) month = "Mar";
else if(strcmp(monthnum.c_str(),"04") == 0) month = "Apr";
else if(strcmp(monthnum.c_str(),"05") == 0) month = "May";
else if(strcmp(monthnum.c_str(),"06") == 0) month = "Jun";
else if(strcmp(monthnum.c_str(),"07") == 0) month = "Jul";
else if(strcmp(monthnum.c_str(),"08") == 0) month = "Aug";
else if(strcmp(monthnum.c_str(),"09") == 0) month = "Sep";
else if(strcmp(monthnum.c_str(),"10") == 0) month = "Oct";
else if(strcmp(monthnum.c_str(),"11") == 0) month = "Nov";
else if(strcmp(monthnum.c_str(),"12") == 0) month = "Dec";
newdate = "\"" + month + " " + date.substr(8,2) + " " + date.substr(0,4) + " " + newtime + "\"";
system("date --set newdate");
return 0;
}
运行此代码时发生如下错误:
日期:无效日期“newdate”
我无法理解这些代码的问题 “无效日期”部分是因为它实际执行“日期--设置新日期”。您希望它执行“date--set[newdate变量的值]”
改变
system("date --set newdate");
到
sprintf
可以是另一个选项
sprintf(newdate,"date --set %s %s %s %s", month, date.substr(8,2), date.substr(0,4), newtime);
system(newdate);
只需检查变量的类型是否为
string
或upur平台支持sprintf
对于崩溃,请在调试器中运行程序。对于newdate
问题,请考虑如何将变量的值放入字符串中。将日期设置为用户输入的结果听起来像是灾难。请考虑配置NTP属性,请远离键盘。您确定您有足够的权限设置系统时间吗?普通用户不会。这会不会变成一个std::string
?请记住,system
使用了一个旧的C样式字符串。这可能是正确的-我显然有点生疏了。将尝试找出正确的语法。@JoachimPileborg谢谢。当我试着编译和运行它时,它已经被修改成了可以正常工作的东西代码>?@mvp我完全同意。我只是在评论上面提出的解决方案。实际上,我会尝试使用settimeofday
确定OP的解决方案为什么不起作用。
sprintf(newdate,"date --set %s %s %s %s", month, date.substr(8,2), date.substr(0,4), newtime);
system(newdate);