MSH
MSH

Reputation: 429

set system date and time within c++ program in linux

In my program user selects date and time in an extjs form and then data will be send to the server side (c++ program). In the server program date and time will be applied to the system as below:

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;
}

But when running this code system crashes! I have another code for applying date and time:

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;
}

when running this code an error was occurred as below: date: invalid date "newdate"

I can't understand the problem of these codes!

Upvotes: 0

Views: 11435

Answers (2)

siji
siji

Reputation: 1

sprintf can be another option...

sprintf(newdate,"date --set %s %s %s %s", month, date.substr(8,2), date.substr(0,4), newtime);
system(newdate);

just check if the variable is of type string or upur platform support sprintf.

Upvotes: 0

Deestan
Deestan

Reputation: 17136

The "invalid date" part is because it actually executes "date --set newdate". You want it to execute "date --set [value of newdate variable]".


Change

system("date --set newdate");

to

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

Upvotes: 2

Related Questions