如何获得UTC时间

Jas*_*lls 5 c++ linux ubuntu time utc

我正在编写一个小程序来下载气象软件包使用的相应文件集.这些文件的格式YYYYMMDDYYYYMMDD HHMMUTC 类似.我想知道C++中UTC的当前时间,我在Ubuntu上.有一个简单的方法吗?

Dir*_*tel 8

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); 
}        
Run Code Online (Sandbox Code Playgroud)

我根据手册页中的内容添加了一个完整的示例:

$ gcc -o strftime strftime.c 
$ ./strftime
Mon, 16 Dec 13 19:54:28 +0000
$
Run Code Online (Sandbox Code Playgroud)


nur*_*tin 6

你可以使用gmtime:

struct tm * gmtime (const time_t * timer);
Convert time_t to tm as UTC time
Run Code Online (Sandbox Code Playgroud)

这是一个例子:

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;
}
Run Code Online (Sandbox Code Playgroud)

ideone链接:http://ideone.com/pCKG9K

  • 你应该使用`std :: strftime(buf,sizeof buf,...)`.值得注意的是,`return buf;`只是因为该值被隐式转换为`std :: string`而有效; 如果`now`返回一个`char*`(就像在C中那样),你将返回一个指向本地对象的指针,这是一个很大的禁忌. (5认同)
  • 注意:如果可能的话,你可能想要使用`gmtime_r`,而非标准的,同时是重入和数据争用的安全. (3认同)