Linux 如何获得UTC时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20619236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get UTC time
提问by Jason Mills
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?
我正在编写一个小程序来下载气象软件包要使用的适当文件集。该文件是一样的格式YYYYMMDD
,并YYYYMMDD HHMM
在UTC。我想知道C++中 UTC 的当前时间,我在 Ubuntu 上。有没有一种简单的方法可以做到这一点?
采纳答案by Dirk Eddelbuettel
A high-end answer in C++ is to use Boost Date_Time.
C++ 中的高端答案是使用 Boost Date_Time。
But that may be overkill. The C library has what you need in strftime
, the manual page has an example.
但这可能是矫枉过正。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);
}
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
$
回答by nurettin
You can use gmtime:
您可以使用 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;
}
ideone link: http://ideone.com/pCKG9K
ideone 链接:http://ideone.com/pCKG9K