c++ - 在 linux 中的 c++ 程序中设置系统日期和时间

标签 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_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”。您希望它执行“date --set [newdate 变量的值]”。


改变

system("date --set newdate");

string cmd = "date --set ";
cmd += newdate;
system(cmd.c_str());

关于c++ - 在 linux 中的 c++ 程序中设置系统日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18483061/

相关文章:

linux - 无法使用 ceph-deploy : Error EACCES: access denied 部署 Ceph 管理器守护进程

c++ - 缓冲区溢出的第一次实验

date - SAS 根据年龄查找出生日期

ruby-on-rails - Bootstrap 日期选择器禁用日期

c++ - 具有 Python GUI 和 C++ 后台模块的混合应用程序

c++ - 如何使用 POCO 库将 C++ 对象传输到 Web 服务

c++ - 前向声明类指定大小

c++ - 通过 C++ 中的组合实现多态行为,无需多级继承

c - 64 位但不是 32 位构建中的 glib.h 负数组大小错误

php - 如何将 MySql DATETIME 结果放入 datetime-local 类型的 HTML 输入中