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?

有帮助吗?

解决方案

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
$

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top