Search code examples
ctimestampiso8601

Regarding timestamp in C


I am trying to get a timestamp in the YYYY-MM-DDTHH:MM:SS.SSS+HH:MM format, for e.g. 2021-10-28T07:31:56.345+05:30. The nearest I could achieve was 2021-11-03T13:06:43+0530. Notice the missing SSS after the seconds field and the missing : in 0530. This is what I have done:

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

void current_time(char* str)
{
        time_t timer;
        struct tm* tm_info;

        time(&timer);
        tm_info = localtime(&timer);

        strftime(str, 50, "%FT%T%z", tm_info);
}

int main(void)
{
        char str[50];
        current_time(str);
        printf("%s\n", str);
}

Any help would be appreciated. Thank you.


Solution

  • Perhaps you could use timespec_get which gets the time including nanoseconds.

    #include <stdio.h>
    #include <time.h>
     
    void current_time(char* str, size_t len) {
        if(len < 30) { // the final string is 29 chars + '\0'
            str[0] = '\0';
            return;
        }
    
        struct timespec ts;
        // get timestamp inc. nanoseconds
        timespec_get(&ts, TIME_UTC);
    
        // get the second part of the timespec:
        struct tm lt = *localtime(&ts.tv_sec);
    
        // format the beginning of the string
        size_t w = strftime(str, len, "%FT%T.", &lt);
    
        // add milliseconds
        w += sprintf(str + w, "%03d", (int)(ts.tv_nsec / 1000000));
        
        // get zone offset from UTC 
        char zone[6];
        strftime(zone, sizeof zone, "%z", &lt);
    
        if(zone[0]) { // check that we got the offset from UTC
            // add the zone to the resulting string
            w += sprintf(str + w, "%.3s:", zone);
            w += sprintf(str + w, "%.2s", zone + 3);
        }
    }
    
    int main(void) {
        char buff[100];
        current_time(buff, sizeof buff);
    
        printf("Timestamp: %s\n", buff);
    }
    

    Possible output:

    Timestamp: 2021-11-03T10:05:06.696+01:00
    

    Which matches your wanted format:

               YYYY-MM-DDTHH:MM:SS.SSS+HH:MM