Set System date and time using C++ in Linux

You understand wrongly. settimeofday(2) is setting the Epoch time. which is both date and time. Read time(7)

So you if you start from a string expressing a date, convert that string with strptime(3) to a struct tm then convert that to a Unix time with mktime(3) then feed that to settimeofday (i.e. the tv_sec field).

However, settimeofday requires root privilege and I believe you usually should avoid calling it (at least on usual, Internet-connected, computers). Better set some NTP client service on your Linux PC (e.g. run ntpd or chrony and more generally read the sysadmin chapter on keeping time...). See also adjtimex(2)

BTW, changing abruptly the system time on a multi-tasking system -like Linux or Windows- is a very dangerous operation (since it will upset and disturb a lot of system tasks depending or using the time). There are few good reasons to do that (it is a very bad idea in general). If you do that, do that with very few programs & services running (e.g. single user mode Linux). You should not do that in ordinary application code.


I write this piece of code to set Date and Time under Linux.

#include <time.h>

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

Note that stime requires root privileges.