0

Because the compiler the code will run on doesn't accept _mkgmtime and only mktime, I am forced to use mktime to convert broken down time to Unix TimeStamp and viceversa.

The old solution was to use _mkgmtime and gmtime to convert from broken down time to UNIX timestamp and viceversa. This worked until I tried to compile it and use it on my microcontroller.

Now, I have to somehow use mktime to generate UNIX timestamp from broken-down time and then to convert from broken-down time to UNIX timestamp. Both in UTC

Cris
  • 4,004
  • 16
  • 50
  • 74
  • Maybe set the time zone to UTC? – Bodo Jun 02 '22 at 14:27
  • `mktime()` and `gmtime()` are standard library functions since C89. I have no idea what `_mkgmtime()` is, but it looks like a Microsoftism. One should always take care when engaging platform-specific features, due to their essential non-portability. – John Bollinger Jun 02 '22 at 14:30
  • Bodo, how would I do that by just setting the small part of my code to UTC time zone? An example would be lovely, thank you. – Cris Jun 02 '22 at 14:54
  • See my comment [here](https://stackoverflow.com/questions/72305183/how-to-convert-unix-time-stamps-utc-to-broken-down-time/72305539#comment128035542_72305539). – Steve Summit Jun 02 '22 at 15:35
  • On a Posix system — which it sounds like yours is *not*, but anyway — the acepted way of setting the timezone is to call e.g. `putenv("TZ=UTC")`, then call `tzset()`. (And if necessary you can fetch the old `TZ` value with `getenv` first, so you can set it back when your'e done.) This is admittedly a kludge and a nuisance, and I suspect it won't work in your environment, but theoretically it's one option. – Steve Summit Jun 02 '22 at 15:42

1 Answers1

0

Is it possible to force mktime() to return a timestamp in UTC always?

The C language specification says that the return value of mktime() is encoded the same way as that of time(), but it explicitly leaves that encoding unspecified. Thus, the answer depends on the C implementation where your code will run.

On a POSIX system such as Linux, time() returns an integer number of seconds since the epoch, which is defined in terms of UTC, not local time. Therefore, if your target machine is such a system then you don't need to do anything to get mktime to return a UTC timestamp.

HOWEVER, mktime assumes that its input is expressed in broken-down local time, and it will use the configured time zone (which is not included in the broken-down time) to perform the calculation. How the local time zone is configured is system dependent.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157