Search code examples
cmakeunix-timestamp

How do I convert a UNIX timestamp to ISO in CMake


I have a UNIX-style timestamp that looks like 1587405820 -0600 which I would like to convert to an ISO style format, something like YYYY-MM-DDTHH:MM:SSZ

CMake has a string(TIMESTAMP ...) command at https://cmake.org/cmake/help/v3.12/command/string.html#timestamp but this only gets me the current time in a formatted string which does not work for my application. I need to be able to convert an existing time into ISO format.

Is there a way to do this?


UPDATE

Based on @squareskittles answer, here's what I ended up with this test which is doing the right thing:

# Check that we get the current timestamp
string(TIMESTAMP TIME_T UTC)
message(STATUS ">>> T1: ${TIME_T}")

# Get the ISO string from our specific timestamp
set(ENV{SOURCE_DATE_EPOCH} 1587405820)
string(TIMESTAMP TIME_T UTC)
unset(ENV{SOURCE_DATE_EPOCH})
message(STATUS ">>> T2: ${TIME_T}")

# Check that we get the current timestamp again correctly
string(TIMESTAMP TIME_T UTC)
message(STATUS ">>> T3: ${TIME_T}")

Which gives me this output:

-- >>> T1: 2020-04-22T15:08:13Z
-- >>> T2: 2020-04-20T18:03:40Z
-- >>> T3: 2020-04-22T15:08:13Z

Solution

  • If you want this function to use a specific time other than than the current time, you can set the environment variable SOURCE_DATE_EPOCH to the UNIX-style timestamp (integer):

    # Set the environment variable to a specific timestamp.
    set(ENV{SOURCE_DATE_EPOCH} 1587405820)
    # Convert to ISO format, and print it.
    string(TIMESTAMP MY_TIME)
    message(STATUS ${MY_TIME})
    

    prints (for UTC -0600):

    2020-04-20T12:03:40
    

    If you need to adjust this time to UTC time, you can add the UTC argument:

    set(ENV{SOURCE_DATE_EPOCH} 1587405820)
    string(TIMESTAMP MY_TIME UTC)
    message(STATUS ${MY_TIME})
    

    prints:

    2020-04-20T18:03:40Z
    

    Note: If this SOURCE_DATE_EPOCH variable is used elsewhere in your CMake code, it is best to save the SOURCE_DATE_EPOCH value before modifying it, so it can be set back to its previous value when complete.