Search code examples
c++linuxubuntutimeutc

How to get UTC time


I'm programming a small little program to download the appropriate set of files to be used by a meteorological software package. The files are in format like YYYYMMDD and YYYYMMDD HHMM in UTC. I want to know the current time in UTC in C++ and I'm on Ubuntu. Is there a simple way of doing this?


Solution

  • A high-end answer in C++ is to use Boost Date_Time.

    But that may be overkill. The C library has what you need in strftime, the manual page has an example.

    /* from man 3 strftime */
    
    #include <time.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[]) { 
        char outstr[200];
        time_t t;
        struct tm *tmp;
        const char* fmt = "%a, %d %b %y %T %z";
    
        t = time(NULL);
        tmp = gmtime(&t);
        if (tmp == NULL) {
            perror("gmtime error");
            exit(EXIT_FAILURE);
        }
    
        if (strftime(outstr, sizeof(outstr), fmt, tmp) == 0) { 
            fprintf(stderr, "strftime returned 0");
            exit(EXIT_FAILURE); 
        } 
        printf("%s\n", outstr);
        exit(EXIT_SUCCESS); 
    }        
    

    I added a full example based on what is in the manual page:

    $ gcc -o strftime strftime.c 
    $ ./strftime
    Mon, 16 Dec 13 19:54:28 +0000
    $