【问题标题】:How to get UTC time [duplicate]如何获取UTC时间[重复]
【发布时间】:2014-01-04 08:01:51
【问题描述】:

我正在编写一个小程序来下载气象软件包使用的适当文件集。这些文件的格式类似于 UTC 中的 YYYYMMDDYYYYMMDD HHMM。我想知道 C++ 中 UTC 的当前时间,我在 Ubuntu 上。有没有一种简单的方法可以做到这一点?

【问题讨论】:

  • 您能否重申这个问题:您想重新格式化文件名从 UTC 到本地吗?还是您想访问当前时间为 UTC?
  • 只需访问 UTC 中的当前时间,对不起,我会编辑问题。

标签: c++ linux ubuntu time utc


【解决方案1】:

你可以使用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;
}

输出:

20131220 19:33:51

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

【讨论】:

  • 你应该使用std::strftime(buf, sizeof buf, ...)。还值得注意的是,return buf; 之所以有效,只是因为该值被隐式转换为std::string;如果now 返回一个char*(在C 中可能会这样),您将返回一个指向本地对象的指针,这是一个很大的禁忌。
  • 注意:如果可能的话,您可能想使用gmtime_r,虽然它是非标准的,但它是可重入和数据竞争安全的。
  • @MatthieuM。你是对的,我通常会检查 gmtime_r 的存在。我认为这个答案有点矫枉过正。感谢您提供有用的反馈。
【解决方案2】:

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
$

【讨论】:

  • strftime 手册页示例使用 localtime()。 OP 将需要 gmtime() 来获取 UTC 时间。
  • 使用 strftime 似乎是最好看的选择。谢谢。如有必要,我可以手动转换为 UTC,但我想看看 nos 说了什么。
  • @nos 如何使用 gmtime() 计算夏令时?
  • @JasonMills UTC 没有夏令时。时间(空);应该返回正确的东西,你可以传递给 gmtime();
  • @JasonMills: (a) gmtime 为您提供 UTC,而不是 GMT,并且 UTC 与任何时区无关; (b) GMT 无论如何都是一个时区。 :) 应用 DST 时,英国会切换到 BST。
猜你喜欢
  • 2011-12-24
  • 2013-09-19
  • 2011-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多