Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get UTC time [duplicate]

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?

like image 383
Jason Mills Avatar asked Dec 16 '13 19:12

Jason Mills


1 Answers

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
$
like image 176
Dirk Eddelbuettel Avatar answered Sep 20 '22 12:09

Dirk Eddelbuettel