How to get UTC time
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
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
$