Skip to content
Advertisement

Set System date and time using C++ in Linux

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

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

As far as I understood settimeofday() does nothing with the date and I am not sure about the usage of function stime(). I hope mktime() has nothing to do with my need.

Can anybody help me.

Advertisement

Answer

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.

Advertisement