在linux中的c++程序中设置系统日期和时间
set system date and time within c++ program in linux
在我的程序中,用户在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_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("%dn%dn%dn%dn%dn", 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");
至
string cmd = "date --set ";
cmd += newdate;
system(cmd.c_str());
sprintf
可以是另一个选项。。。
sprintf(newdate,"date --set %s %s %s %s", month, date.substr(8,2), date.substr(0,4), newtime);
system(newdate);
只需检查变量的类型是string
还是upur平台支持sprintf
。
相关文章:
- C++,系统无法执行指定的程序
- 查询SQLite数据库中的日期
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 在UNIX系统中使用DIR查找文件的字节大小
- 错误处理.将系统错误代码映射到泛型
- 当系统的卷被修改时,如何修改WASAPI环回捕获卷
- 如何使用套接字编程获取系统日期和时间
- 自动更新QDateTimeEdit,以便它显示当前的系统日期和时间
- 执行循环,直到系统时间到达特定日期/时间
- 如何在 c++ 中将用户日期与系统日期进行比较
- Qt资源系统中文件的最后修改日期
- 在linux中的c++程序中设置系统日期和时间
- 从系统中拆分日期和时间::DateTime
- Apache Qpid/Redhat MRG-以可移植的方式跨不同系统发送日期
- 获取Win32系统日期格式字符串
- c++不能在当前系统时间和日期之后命名txt文件
- 如何在我的C++程序中的特定日期/驱动器已满后删除linux系统中的文件
- 如何从系统日期获取昨天的日期并附加到字符串?
- 如何以秒为单位获取系统的当前日期时间
- 在c++中传递系统日期和时间作为文件名