baoky chen
baoky chen

Reputation: 837

C++ Linux - Change Timezone to a certain timezone

I am trying to synchronize my server time with client time, I got the code to fetch the server time, which is below. If I run it in server, upon client login. I will send time to the client, but how do I change the "client" system time to the time I send from the server.

I googled about setenv and such, but how do we actually change the time in Linux C++?

Using the code below, I can get the current time:

/* localtime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );

  return 0;
}

Upvotes: 1

Views: 3944

Answers (1)

A Linux (or Unix, or Posix) system measures the time from the unix epoch. No timezone is really involved at the lowest level (the time related syscalls, and the kernel). Timezone are a library thing, thru localtime(3) and strftime(3) and other functions.

Read also the time(7) man page.

You really want to synchronize time (on both local and remote machines) using the NTP protocol (use ntpd, chrony, ntpdate ....), or at least rdate (but NTP is preferable).

The system calls to query the time are gettimeofday(2), time(2), clock_gettime(2) with CLOCK_REALTIME

You might use settimeofday(2) and adjtimex(2) syscalls to set the time. This usually requires root privilege.

Upvotes: 3

Related Questions