12

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?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Jason Mills
  • 585
  • 2
  • 6
  • 20

2 Answers2

11

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
$
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
9

You can use gmtime:

struct tm * gmtime (const time_t * timer);
Convert time_t to tm as UTC time

Here's an example:

std::string now()
{
  std::time_t now= std::time(0);
  std::tm* now_tm= std::gmtime(&now);
  char buf[42];
  std::strftime(buf, 42, "%Y%m%d %X", now_tm);
  return buf;
}

Output:

20131220 19:33:51

ideone link: http://ideone.com/pCKG9K

Andrew
  • 5,839
  • 1
  • 51
  • 72
nurettin
  • 11,090
  • 5
  • 65
  • 85
  • 6
    You should use `std::strftime(buf, sizeof buf, ...)`. It's also worth noting that the `return buf;` is valid only because the value is implicitly converted to a `std::string`; if `now` returned a `char*` (as it likely would in C), you'd be returning a pointer to a local object, which is a big no-no. – Keith Thompson Dec 16 '13 at 19:48
  • 3
    Note: if possible you might want to use `gmtime_r` instead, which whilst non-standard, is both re-entrant and data-race safe. – Matthieu M. Dec 16 '13 at 19:51
  • @MatthieuM. you're correct, I would normally have a check for the existence of gmtime_r. I thought it was overkill for this answer. Thanks for useful feedback. – nurettin Dec 16 '13 at 19:52