Set System Date and Time Using C++ in Linux

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.

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

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

How do you set system time using C/C++?

Using the IAR toolset the time of day C runtime API (time()) can be overridden using the example in ARM\src\lib\time.c. The default routine always returns -1, an indication that the CRT has no idea what time it is. Once you provide your own implementation of time(), which will obtain the time of day from a source that depends on your tartget platform and/or RTOS, you can set the time of day by updating whatever that time source is. IAR may well have already done this for their RTOS - I haven't used IAR's PowerPac RTOS.

The details of how this works for another RTOS or a system with no RTOS is outlined in the IAR C/C++ Development Guide.

For example, on a system I've worked on that uses an ST Micro STM32 microscontroller, the real time clock (RTC) is set to tick once per second, and the time() library function simply returns the value in the RTC. Setting a new date/time is a matter of setting the RTC with a new value. The RTC's time counter is set with a Unix epoch value (seconds since 1 Jan 1970), which allows the rest of the library functions from time.h to work just fine (up to some time around in 2035 when 32-bit overflows start wreaking havoc).

The calendar routines in the IAR DLIB C runtime library support dates through 2035-12-31 (they overflow before 2038 I suspect because internal calcuations use a 1 Jan 1900 epoch). If you use the Unic epoch, the other DLIB routines more or less just work - I'm not sure what level of effort would be required to use a different epoch.

system time setting using c library function

if you don't want to execute a shell command you can (as you mentioned) use the settimeofday, i would start by reading the MAN page, or looking for some examples

here's an example:

#include <sys/time.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char *argv[])
{
struct timeval now;
int rc;

now.tv_sec=866208142;
now.tv_usec=290944;

rc=settimeofday(&now, NULL);
if(rc==0) {
printf("settimeofday() successful.\n");
}
else {
printf("settimeofday() failed, "
"errno = %d\n",errno);
return -1;
}

return 0;
}

Shamelessly ripped From IBMs documentation, the struct timeval struct holds the number of seconds (as a long) plus the number of microseconds (as a long) from 1 January 1970, 00:00:00 UTC (Unix Epoch time). So you will need to calculate these numbers in order to set the time. you can use these helper functions, to better handle dealing with the timeval struct.

How to generate current datetime with system's regional format in C++?

First, we configure the locale for the user's default by imbuing the output stream with the empty-name locale (locale("")). Then we use the locale-dependent date and time formats with std::put_time. For example: Live On Coliru

#include <ctime>
#include <iomanip>
#include <iostream>

int main() {
std::time_t raw_now = time(nullptr);

std::tm now = *localtime(&raw_now);

std::cout.imbue(std::locale(""));
std::cout << std::put_time(&now, "My locale: %x %X\n");

// For comparison, how we'd expect it to show up for a
// user configured for Great Britain:
std::cout.imbue(std::locale("en_GB.UTF-8"));
std::cout << std::put_time(&now, "Great Britain: %x %X\n");
}

On my box (configured for the US), this produces the following output:

My locale: 02/16/2022 06:05:48 PM
Great Britain: 16/02/22 18:05:48

There is also a %c format to produce date and time, but this (at least normally) includes the day of the week (e.g., Wed 16 Feb 2022 18:11:53 PST) which doesn't fit with what you seem to want.

As a side-note: all compilers are supposed to accept at least "C" and "" for locale names. Any other name (like the en_GB.UTF-8 I've used above) depends on the compiler. You may need a different string if you're using a different compiler (I was testing with g++ on Linux).

How to get the date and time values in a C program?

Use time() and localtime() to get the time:

#include <stdio.h>
#include <time.h>

int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("now: %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}


Related Topics



Leave a reply



Submit