我正在编写一个小程序来下载气象软件包使用的相应文件集.这些文件的格式YYYYMMDD
与YYYYMMDD HHMM
UTC 类似.我想知道C++中UTC的当前时间,我在Ubuntu上.有一个简单的方法吗?
C++中的高端答案是使用Boost Date_Time.
但这可能是矫枉过正的.C库有你需要的东西strftime
,手册页有一个例子.
/* 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); }
我根据手册页中的内容添加了一个完整的示例:
$ gcc -o strftime strftime.c $ ./strftime Mon, 16 Dec 13 19:54:28 +0000 $
你可以使用gmtime:
struct tm * gmtime (const time_t * timer); Convert time_t to tm as UTC time
这是一个例子:
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; }
ideone链接:http://ideone.com/pCKG9K