C 将NTP服务器返回的时间转换为字符串



我是C 的新手,想从NTP服务器转换为人类可读日期时间值。

void printTime() {
  /*
  Human time (GMT): Friday, May 17, 2019 8:44:16 AM
  Human time (your time zone): Friday, May 17, 2019 10:44:16 AM GMT+02:00
  */
  unsigned long e = 1558082656;
  time_t epoch = e;
  struct tm *timeinfo_e;
  char buf[80];
  time(&epoch);
  timeinfo_e = gmtime(&epoch);
  std::cout << "epoch: " << asctime(timeinfo_e) << std::endl;
  strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", timeinfo_e);
  printf("%sn", buf);
}

,但它显示了当前时间,而不是该时期值的时间。有什么问题?

谢谢!

time(&epoch);

这将当前时间存储到epoch中,覆盖您先前分配的值。如果您取出该内容,您的程序将显示您分配给epoch的UNIX时间。

但是,C 具有其自己的DateTime库,并且计划得到极大改进的C 20,它应该能够完全避免C API。截至今天,您已经可以看到我称之为理解代码的改进:

#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
namespace chr = std::chrono;
void printTime() {
  using Clock = chr::system_clock;
  unsigned long e = 1558082656;
  chr::time_point<Clock> time(chr::seconds{e});
  auto c_time = Clock::to_time_t(time); // Gone if using C++20's to_stream function
  std::cout << std::put_time(std::gmtime(&c_time), "%c %Z"); // localtime for the user's timezone
}

,如果您觉得当前有一些回旋处要转到time_point并返回,尽管自时钟时代以来明确指示了几秒钟,则put_time仍然可以用作打印C时间的更方便的方法。

<</p> <</p> <</p>

最新更新