Setting system date and time using C ++ on Linux

I am developing a cross-platform application that changes the system date and time to a specified value. I have completed the part for Windows.

How to set system date and time from program C++to Linux? I am looking for a function similar to SetSystemTime(SYSTEMTIME &x).

As far as I understand, settimeofday()it does nothing with the date, and I'm not sure about the use of the function stime(). Hope that mktime()has nothing to do with my need.

Can anybody help me.

+5
source share
3 answers

. settimeofday (2) . . (7)

, , , strptime (3) struct tm Unix mktime (3), settimeofday settimeofday (. tv_sec tv_sec).

settimeofday , , ( , , ). - NTP (, ntpd chrony , , sysadmin ...) adjtimex (2)

, -like Linux Windows- - ( ). ( ). , (, Linux). .

+5

, Date Time Linux.

struct tm time = { 0 };

time.tm_year = Year - 1900;
time.tm_mon  = Month - 1;
time.tm_mday = Day;
time.tm_hour = Hour;
time.tm_min  = Minute;
time.tm_sec  = Second;

if (time.tm_year < 0) time.tm_year = 0;

time_t t = mktime(&time);

if (t != (time_t) -1)
    stime(&t);

, stime root . , .

Boshen

+2

@guan Boshen, , " Linux". ? QT C++

0

All Articles