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

Jeff picture Jeff · Sep 14, 2009 · Viewed 9.6k times · Source

I have an embedded system (ARM 9263) running an RTOS, IAR tools. The system supports the standard time() function which gives me the current time. I need the reverse call, that is I need to set the time - is there a "C" standard way to do this? I've googled around, sure thought it would be obvious, but perhaps it is platform dependent? I'm not sure why, since time() is not - any ideas? Thanks!

Answer

Michael Burr picture Michael Burr · Sep 14, 2009

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.